I know Ruby has a bunch of useful operators, like ||=
What other tricky operators does it have?
I haven't found any references for it.
I know Ruby has a bunch of useful operators, like ||=
What other tricky operators does it have?
I haven't found any references for it.
The ampersand at the end of a method signature will grab and expect a block for you.
def foo(bar, &block)
block.call (bar += 1)
end
The ampersand can also be used in this form to call to_proc
and let you call the :address
method with a symbol (example is borrowed from elsewhere)
@webs ||= Web.find(:all).index_by &:address
The shortcuts like +=
and -=
are handy.
Not an operator, so much as another shortcut Rails makes possible. This will get you bar when foo is either nil?
or false
a = foo || bar
In terms of "operators" I found an (unofficial) thing here for reference: Ruby operators
I find that the splat operator is one of the trickiest Ruby operators:
It splits arrays:
a,b,c = *[1,2,3]
Or builds an array:
*a = 1,2,3
It can also be used in case
statement:
first = ["one", "two"]
second = ["three", "four"]
case number
when *first
"first"
when *second
"second"
end
It can be used as function argument for varargs:
def stuff *args
args.join('|')
end
As it is used for both (splitting and creating arrays), I always have to check the syntax before using it. It can be used for so many purposes (like converting a hash to an array) that I really find it hard to master.
<=> the "spaceship" or comparison operator
=== the "trequals" or case matching operator