Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricky operators in Ruby [closed]

Tags:

ruby

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.

like image 562
AntonAL Avatar asked Sep 03 '26 19:09

AntonAL


2 Answers

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.

like image 152
Sébastien Le Callonnec Avatar answered Sep 05 '26 15:09

Sébastien Le Callonnec


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

like image 38
ebeland Avatar answered Sep 05 '26 15:09

ebeland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!