Difficult operators in Ruby

I know that Ruby has a bunch of useful operators, like ||=

What other complex operators does he have?

I did not find any links for this.

+3
source share
3 answers

Ampersand at the end of the method signature will capture and expect a block for you.

def foo(bar, &block)  
   block.call (bar += 1)  
end

Ampersand can also be used in this form to call to_procand let you call a method :addresswith a symbol (example borrowed from another place)

@webs ||= Web.find(:all).index_by &:address

Shortcuts such as +=and -=are convenient.

Not a statement, but another Rails shortcut makes it possible. This will give you a bar when foo - nil?orfalse

a = foo || bar

In terms of “operators”, I found here a (unofficial) thing for reference: Ruby operators

+5
source

, splat Ruby:

:

a,b,c = *[1,2,3]

:

*a = 1,2,3

case:

first = ["one", "two"]
second = ["three", "four"]

case number
  when *first
    "first"
  when *second
    "second"
end

varargs:

def stuff *args
   args.join('|')
end

( ), . (, ), .

+5
<=> the "spaceship" or comparison operator
=== the "trequals" or case matching operator
+1
source

Source: https://habr.com/ru/post/1795045/


All Articles