Reputation: 786
One pattern I like to implement in order to make my code more declarative is to replace a long conditional like this:
def make_a_decision(value)
if value == 1
"One"
elsif value == 2
"Two"
elsif value == 3
"Three"
end
end
With a hash like this:
def make_a_decision(value)
{ 1 => "One",
2 => "Two",
3 => "Three"
}[value]
end
I like doing this because it replaces a conditional with an object that simply needs to respond to []
. It's also easier to read, in my opinion, partly due to the DRY nature of the hash.
I don't see any other Rubyists doing this, though. Why not?
Upvotes: 0
Views: 156
Reputation: 361
Upvotes: 0