D
Derek Michael
Hi Guys,
Please have patience with my possibly basic basic question. I am
learning Ruby and studying blocks/closures right now and confused
without being able to find an answer. I was studying and first came
across this example
[1,2,3].each {|x| puts "This is #{x}. "}
and this makes sense to me I believe. for each object (which is
integers 1, 2, 3), it runs the {} block code, passing in the integer
objects in as variable 'x', then puts out the string including the 'x'
variable.
Now what gets me confused is once I get to these following examples:
class MyClass
def command1()
yield(Time.now)
end
end
m = MyClass.new
m.command1() {|x| puts "Current time is #{x}"}
In the above example, how does 'x' get the Time.now value? In the first
code I have above, 'x' becomes the actual integer object (1, 2, and 3).
So in this case, how does the 'x' variable in this block code get the
Time.now value when executed through yield?
I hope my question even makes sense. I'm hoping by asking I can clarify
any mistaken ideas I have on blocks/closures.
Please have patience with my possibly basic basic question. I am
learning Ruby and studying blocks/closures right now and confused
without being able to find an answer. I was studying and first came
across this example
[1,2,3].each {|x| puts "This is #{x}. "}
and this makes sense to me I believe. for each object (which is
integers 1, 2, 3), it runs the {} block code, passing in the integer
objects in as variable 'x', then puts out the string including the 'x'
variable.
Now what gets me confused is once I get to these following examples:
class MyClass
def command1()
yield(Time.now)
end
end
m = MyClass.new
m.command1() {|x| puts "Current time is #{x}"}
In the above example, how does 'x' get the Time.now value? In the first
code I have above, 'x' becomes the actual integer object (1, 2, and 3).
So in this case, how does the 'x' variable in this block code get the
Time.now value when executed through yield?
I hope my question even makes sense. I'm hoping by asking I can clarify
any mistaken ideas I have on blocks/closures.