garbagecollector
garbagecollector

Reputation: 3880

Ruby DSL: Can you pass a block to an object

I'm quite new to Ruby and just exploring around with DSL. I'm wondering if this is possible in Ruby, and if so, how would one do this?

melissa = Player.new
melissa do
  on :turn do
    puts "It's my turn!"
  end

  on :win do
    puts "I win! Hahahaha"
  end
end

Excuse me if this has been asked before. I'm not sure what to search for this problem. Searching for DSL yields other things.

Upvotes: 3

Views: 169

Answers (1)

Guilherme Bernal
Guilherme Bernal

Reputation: 8303

Sure you can. Here's a sample, try to modify it:

class Player
    def initialize(&block)
        @actions = {}
        instance_eval &block
    end
    def on(action, &block)
        @actions[action] = block
    end
    def act(action)
        @actions[action].call if @actions[action]
    end
end

melissa = Player.new do
  on :turn do
    puts "It's my turn!"
  end

  on :win do
    puts "I win! Hahahaha"
  end
end

melissa.act :turn   #=> It's my turn!

Upvotes: 3

Related Questions