Nick Ginanto
Nick Ginanto

Reputation: 32130

Ruby Proc syntax usage

my_proc = proc{|x| "this is #{x}"}

given my_proc, what makes the following syntax work?

my_proc.call("x") # makes sense

my_proc.("x") # not really sure but ok

my_proc["x"] # uhhh....

my_proc === "x" # what the deuce?!

Upvotes: 0

Views: 125

Answers (3)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

Since you are specifically asking about the syntax, this has nothing to do with Procs. Ruby doesn't allow objects to change the syntax of the language, therefore it doesn't matter what kind of objects we are talking about.

my_proc.call("x")

This is just standard message sending syntax. It sends the message call with the argument "x" to the object returned by evaluating the expression my_proc.

You are asking "what makes this syntax work". Well, this is just how message sending is specified in the Ruby Language Specification.

my_proc.("x")

This is syntactic sugar for my_proc.call("x"), i.e. exactly what we had above: sending the message call with argument "x" to the result of evaluating my_proc.

If you want to make this work for your objects, you need to respond to call.

This syntax was added in Ruby 1.9 to make calling a "function-like object" look more like sending a message, with the only difference being the additional period character. Note that Ruby is not the only language using this syntax, uses it as well.

my_proc["x"]

This is syntactic sugar for my_proc.[]("x"), i.e. sending the message [] with argument "x" to the result of evaluating my_proc.

If you want to make this work for your objects, you need to respond to [].

Proc#[] was added as an alias_method of Proc#call, so that calling a "function-like object" looks more like sending a message, with the only difference being the shape of the brackets. With the addition of the .() syntax sugar in Ruby 1.9, I generally prefer that one.

my_proc === "x"

This is syntactic sugar for my_proc.===("x"), i.e. sending the message === with argument "x" to the result of evaluating my_proc.

If you want to make this work for your objects, you need to respond to ===.

This was added so that Procs could be used as conditions in case expressions and in Enumerable#grep, both of which use === to determine whether or not an object could be subsumed unter a category.

Upvotes: 1

Caillou
Caillou

Reputation: 1500

Ruby often has several syntaxes for the same method, to best fit the develloper needs.

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

About ===:

http://ruby-doc.org/core-2.2.0/Proc.html#method-i-3D-3D-3D

proc === obj → result_of_proc

Invokes the block with obj as the proc's parameter like #call. It is to allow a proc object to be a target of when clause in a case statement.

That means you can use it in case statements, like this:

odd = proc { |x| x % 2 != 0 }
even = proc { |x| x % 2 == 0 }
case 1
when odd then 'odd'
when even then 'even'
end
# => "odd"

Upvotes: 2

Related Questions