Sven S. wrote:
Hi
Cumbersome title, here's what I'd like to do both elegantly and without
monkey patching Hash:
Say, I need to pass a hash to a method:
mymethod :this => 'green'
Now I'd like to include a second hash member only if a condition is met:
mymethod :this => 'green, :that => ('blue' if condition)
This of course leaves ":that => nil" in the hash if the condition is not
met - which is no good, the key should just not be present at all. I
could delete_if after that, but isn't there a more elegant way?
Thanks for your ideas!
Here are two suggestions that are more verbose, but also more readable, especially if you have many arguments or more complex logic:
def with_params
h = {}
yield h
h
end
def mymethod h
p h
end
a = 1
mymethod with_params {|h|
h[:this] = 'green'
h[:that] = 'blue' if a==2
}
You can make this a little tighter, at the expense of changing scope within the block:
class ParamHash < Hash
def method_missing(k, v, *)
self[k] = v
end
end
def with_params2(&block)
ph = ParamHash.new
ph.instance_eval(&block)
ph
end
a = 1
mymethod with_params2 {
this 'green'
that 'blue' if a==2
}
Warning: because of the instance_eval, self is not useful in this block. For example,
something 'red' if @x==1
or
something 'red' if foo()==1
won't work as expected. Also, in this second example, unlike the first, your keys will be limited to symbols which are not instance methods of Object or Kernel (or you could use a blank slate).