0

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?

admdrew
  • 3,790
  • 4
  • 27
  • 39
Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • I think you're looking for how to use a ternary operator in ruby, look here : http://stackoverflow.com/questions/4252936/how-do-i-use-the-conditional-operator-in-ruby – Timothy Groote Dec 19 '14 at 16:31
  • It's not a good use of a ternary statement because there are two possible values for `param`, resulting in a convoluted/multiple ternary. Those are used in Perl and C, but eschewed in Ruby. – the Tin Man Dec 19 '14 at 17:15
  • You are returning `nil` if `param` is neither `:foo` nor `:bar`. Is that your intent, or are those two symbols the only possible values of param? Also, I suggest you remove the Rails tag. (Some users may miss your questions because they've filtered out Rails' questions; others, interested only in Rails questions, will be disappointed that there's no Rails' content.) – Cary Swoveland Dec 19 '14 at 20:25

4 Answers4

3

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.

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
histocrat
  • 2,291
  • 12
  • 21
2

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
vee
  • 38,255
  • 7
  • 74
  • 78
1

You can use a Hash:

def my_method(param)
 objs = {
  foo: "hey",
  bar: "ho"
 }
 objs[param]
end
Aydar Omurbekov
  • 2,047
  • 4
  • 27
  • 53
1

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303