please see the code below, why passing a block to a function then call
block.call in the function will get success, but run block.call out of
a function will get failed?
irb(main):023:0* def myhi(&block)
irb(main):024:1> block.call
irb(main):025:1> end
=> nil
irb(main):026:0> myhi { puts "hi welcome" }
hi welcome
=> nil
irb(main):027:0> { puts "hi welcome" }.call
SyntaxError: (irb):27: syntax error, unexpected tSTRING_BEG, expecting
keyword_do or '{' or '('
{ puts "hi welcome" }.call
^
(irb):27: syntax error, unexpected '}', expecting $end
{ puts "hi welcome" }.call
^
from /usr/bin/irb:12:in `<main>'
Because, as the error message says, this is not valid Ruby syntax. You
can use "lambda" or "proc" instead:
irb(main):001:0> lambda { puts "hi" }.call
hi
=> nil
irb(main):002:0>
But this is really useless, i.e. in that case you should simply do "puts
'hi'". The lambda notation really only makes sense if you want to store
the block away for later usage. Note, that there is also this syntax
(in case you want to structure your code):
begin
puts 'hi'
end
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
An incoming code block will be converted into a Proc object and bound
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
to the block variable. You can pass it around to other methods, call it
directlyusing call,or yield to it as though you’d never bound it to a
variable at all.