0
Can some one explain me this code in ruby about methode explicit and implicit please
Exemple 1 def two_times_implicit return "No block" unless block_given? yield yield end puts two_times_implicit { print "Hello "} # => Hello # => Hello puts two_times_implicit # => No block +++++++++++++++++++++++++++++++++++++++++++++++++++++ Exemple 2 def two_times_explicit (&i_am_a_block) return "No block" if i_am_a_block.nil? i_am_a_block.call i_am_a_block.call end puts two_times_explicit # => No block two_times_explicit { puts "Hello"} # => Hello # => Hello thanks
4 Answers
+ 1
and if you still feels confused, just learn to use more procs in your code. because it's the gift of ruby. it is widely used. as we all know that Fixnum has a method times, so we often use it like:
5.times {puts "hello"}
when we iterate over an array, we write code:
[1, 2, 3].each do |i|
puts i**2
end
why we can write like this? because we are using proc, and maybe the times method each method have the key word "yield" , i guess
+ 1
I got it :
def gretting
return "No block" unless block_given?
yield
yield
end
puts gretting { print "Hello "} # => Hello
# => Hello
puts gretting # => No bloc
0
i don't understand all this terme means in ruby!!
block_given? == { print "Hello "} in puts two_times_implicit { print "Hello "}
i_am_a_block.call == method call?
i_am_a_block.nil? == method call?
Thanks
0
it is just the use of proc, which is a block of code, we can wrap it in an object, store it in an variable, and use it when you want. it is most used after a method. it has two ways to use, {...code...} or do ...code... end. you can call a proc after a method by yield or use the call method of proc.
def hello
if block_given?
yield
else
puts "no block"
end
end
hello #=> no block
hello {puts "hello"} #=> hello
def hello(&use_block)
if block_given?
use_block.call
else
puts "no block"
end
end
hello #=> no block
hello {puts "hello"} => hello
or you can just use proc as a simple object.
use_block = Proc.new {puts "hello"}
use_block.call #=> hello