BlackSoil
BlackSoil

Reputation: 516

What is the semantics of this "do ... end"

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

Upvotes: 1

Views: 87

Answers (2)

numbers1311407
numbers1311407

Reputation: 34072

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 text and background are 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:

class TkLabel
  def initialize(root, &block)
    @root = root

    if block
      # the code inside the block in your app is actually
      # evaluated in the scope of the new instance of TkLabel
      instance_eval(&block)
    end
  end

  def text(value)
    # set the text
  end

  def background(value)
    # set the background
  end
end

Upvotes: 4

Dave Newton
Dave Newton

Reputation: 160311

Second question first: that's just a hash. Create a function that accepts a single argument, and treat it like a hash.

The "semantics" are that initialize accepts a block (the do...end bit), and some methods accepting string parameters to set specific attributes.

Without knowing how you tried to do it, it's difficult to go much beyond that. Here are a few, possible, references that might help you over some initial hurdles.

Ruby is pretty decent at making miniature, internal DSLs because of its ability to accepts blocks and its forgiving (if arcane at times) syntax.

Upvotes: 2

Related Questions