简体   繁体   中英

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?!

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"

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

Since you are specifically asking about the syntax, this has nothing to do with Proc s. 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") , ie 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") , ie 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") , ie 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 Proc s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM