Reputation: 10225
In my Rails app I have this (rather silly) method:
def my_method(param)
foo = "hey"
bar = "ho"
if param == :foo
return foo
elsif param == :bar
return bar
end
end
I don't like the if/else
block, though.
Is there a simpler way to return the value of the local variable foo
if :foo
is provided as a parameter?
Or will I have to use an array or a hash here?
Upvotes: 0
Views: 124
Reputation: 160631
This is really a good time to use a case
statement:
def my_method(param)
case param
when :foo
'hey'
when :bar
'ho'
else
# what do you want to do here?
end
end
Something to consider is, you're using an if
/elseif
, but what happens if neither of those hit? Do you want to return nil, or trap an error? As you look around in other people's code, you'll sometimes find long chains of if
/elseif
tests, with no final else
, which opens up a potential logic error and can result in a hard-to-find bug.
Upvotes: 1
Reputation: 2381
If you're using the very latest Ruby, you can use binding.local_variable_get(param)
. A hash seems cleaner to me, but your mileage may vary.
Upvotes: 3
Reputation: 38645
This should look simpler, don't think introducing a new data structure is required:
def my_method(param)
return 'hey' if param == :foo
return 'ho' if param == :bar
end
Upvotes: 2
Reputation: 2127
You can use a Hash:
def my_method(param)
objs = {
foo: "hey",
bar: "ho"
}
objs[param]
end
Upvotes: 1