Hi
I am learning Ruby and I got the following code from a book.
str=’#{name} is my name, and #{nation} is my nation’
bind=proc do
name,nation=“Stephan”,“Ireland”
binding
end.call
s2=eval(’"’+str+’"’,bind)
puts s2 #This output Stephan is my name, and Ireland is my nation
I did not understand it totally…Could you please tell, what, bind is
doing in s2=eval(’"’+str+’"’,bind)
I did not understand it totally…Could you please tell, what, bind is
doing in s2=eval(‘"’+str+‘"’,bind)
proc do
name,nation=“Stephan”,“Ireland”
binding
end.call
This returns a binding (a relation between variables and values, so to
speak)
that contains the relation between name and nation to “Stephan” and
“Ireland”.
You then assign that binding to variable “bind”.
Now, eval supports a second parameter to specify the binding in which
eval should work. This means that when eval needs to retrieve the value
of
a local variable it will look in the specified binding.
So by evaluating a piece of code that contains name and nation under
the above binding will result in values “Stephan” and “Ireland”.