Make delicious recipes!

Useful operators in ruby



Ruby supports all the normal operators found in other languages like C, Java etc.
Apart from those, it supports some other operators too which can be very useful to know.

# Operator <=> returns -1, 0 or 1 depending upon whether first argument is
# less than, equal to or greater than the second operand. Example:
1 <=> 5
=> -1
10 <=> 5
=> 1
5 <=> 5
=> 0


# Array operator [n] works on numbers too and returns the nth bit.
# Below example shows looping from i to j too in ruby
a=64
30.downto(0) do |n| print a[n] end
0000000000000000000000001000000=> 30


# Numbers allow several functions to be called directly on them which is very convenient.
24.even?
=> true

24.odd?
=> false

1.next.next
=> 3

# to_s(base=10) returns string representation in the given base
16.to_s
=> "16"
16.to_s(2)
=> "10000"
16.to_s(8)
=> "20"
16.to_s(16)
=> "10"








Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal