3

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.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
AntonAL
  • 16,692
  • 21
  • 80
  • 114
  • http://stackoverflow.com/questions/63998/hidden-features-of-ruby. at the very least, check the FAQ section of tag Ruby: http://stackoverflow.com/questions/tagged/ruby?sort=faq&pagesize=50 – sorens Feb 27 '11 at 17:50

3 Answers3

5

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

michaelmichael
  • 13,755
  • 7
  • 54
  • 60
ebeland
  • 1,543
  • 10
  • 21
5

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.

Community
  • 1
  • 1
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
  • 1
    WOW ! Splat operator is awesome ! It makes my code really pure. Thanks a lot ! – AntonAL Mar 04 '11 at 13:07
  • 1
    Both examples work without the splat operator, but a more interesting example is to call a function while "unpacking" the list, e.g., `func(*[1,2,3]). – haridsv Jan 27 '12 at 02:13
  • 2
    Another interesting use for this operator is the partial list unpacking, e.g., `a, *b = [1, 2, 3]`, in which case, `b` is set to `[2, 3]`. – haridsv Jan 27 '12 at 02:20
1
<=> the "spaceship" or comparison operator
=== the "trequals" or case matching operator
Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46