Another option would be to use Object#tap
. This might be better than PinnyM's solution in cases where you're using has_key?
to determine whether to assign a default value (rather than just checking whether the hash returns a truthy value for that key):
def mail(options={})
puts "From: " + (options[:from] || "default@source.com")
puts "To: " + (options[:to] || "other@source.com")
puts "Subject: " + options[:subject]
puts "Body: " + options[:body]
end
me = "Ajedi32"
user = me
custom = "Other Guy"
mail(
{
subject: 'hello',
body: 'world'
}.tap { |opts|
opts[:from] = 'from@source.com' unless user == me
opts[:to] = 'to@destination.com' unless custom == me
}
)
Output:
From: default@source.com
To: to@destination.com
Subject: hello
Body: world
I'm not really sure that's much cleaner than your current solution though...