Arcath
Arcath

Reputation: 4391

Passing a block into a method

I'm trying to work out how you pass blocks into methods.

Basically I have a method, and instead of having the user write this:

def user_config
    @config[:config_value] = "what they want"
end

I'd like them to be able to do this:

user_config do
    :config_value => "what they want"
end

But I dont know how to work with a block in the method.

Upvotes: 0

Views: 1174

Answers (2)

Milan Novota
Milan Novota

Reputation: 15596

Although @diegogs is right and his solution will work just fine, I'd avoid using blocks in such a simple case.

def user_config(config_hash)
  config_hash.each do |k,v|
    @config[k] = v
  end
end

will do just fine

user_config :config_value => "what they want", ...

How about that?

Upvotes: 3

diegogs
diegogs

Reputation: 2076

Blocks are invoked with yield, so this:

def user_config
    yield.each do |k, v|
        @config[k] = v
    end
end

called like this

user_config do
    {:config_value => "what they want"}
end

should work as you want it to. The block returns

{:config_value => "what they want"}

You take the each key in the hash and asign its value in the @config hash.

Upvotes: 3

Related Questions