I am new in ruby and I am confused with the code bock and the parameter.
For example:
"This@is@a @tring".split("@")
In this code,the "This is a string" is an String object,and the split is a method of string object,and the "@" is the parameter for th开发者_开发技巧e split method.
This is really clear since it is the same with other programe language.
However when I see the code block:
[1,2,3].each {|data| puts data}
The [1,2,3] is an array object,the each is one of its method(right?).
for the code block here:
{|data| puts data}
I understand it as a Anonymous function,in javascript,it maybe like this :
function(data){ puts data}
So I think may be I can use the code block as the parameter of the each method. So I try this:
[1,2,3].each ({|data| puts data})
I just add the brace,but it show me some errors.
Why?
Can anyone tell me more about the code block in ruby?
The block is a special part of Ruby syntax. Unlike most things in Ruby, it is not an object, nor is it an argument of the function in the normal sense: methods can only accept one block, and it must come after the argument list. So, in your final example, the parentheses represent the argument list. Putting the block inside that list violates Ruby syntax.
If you're interested in essentially passing around blocks, however, you kinda can. Take a look at the Proc
class, which is kinda like a proxy object for blocks. When a Proc
object is created, it accepts a block parameter. The #call
method on a Proc
passes its arguments to that block.
print_twice = Proc.new { |x| puts x; puts x }
print_twice.call(1) # prints 1 twice
print_twice.call(2) # prints 2 twice
print_twice.call(3) # prints 3 twice
Additionally, with a special syntax, a Proc
can be used as a method call's block:
print_twice = Proc.new { |x| puts x; puts x }
[1, 2, 3].each(&print_twice)
This is equivalent to:
[1, 2, 3].each { |x| puts x; puts x }
The &print_twice
as the final argument of each
essentially passes it as the block. And, since print_twice
is its own object, you can pass it to as many methods as you like.
Hope this helps a bit! :)
- Official doc
- Maybe a better explanation
精彩评论