I am new to Ruby and am learning from reading an already written code.
I encounter this code:
label = TkLabel.new(@root) do
text 'Current Score: '
background 'lightblue'
end
What is the semantics of the syntax “do” above?
I played around with it and it seems like creating a TkLabel object then set its class variable text and background to be what specified in quote. However when I tried to do the same thing to a class I created, that didn’t work.
Oh yeah, also about passing hash into function, such as
object.function('argument1'=>123, 'argument2'=>321)
How do I make a function that accepts that kind of argument?
Thanks in advance
What you’re looking at is commonly referred to as a DSL, or Domain Specific Language.
At first glance it may not be clear why the code you see works, as
textandbackgroundare seemingly undefined, but the trick here is that that code is actually evaluated in a scope in which they are. At it’s simplest, the code driving it might look something like this: