Tintin81
Tintin81

Reputation: 10225

How to call local variable value in a method through a parameter?

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

Answers (4)

the Tin Man
the Tin Man

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

histocrat
histocrat

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

vee
vee

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

Aydar Omurbekov
Aydar Omurbekov

Reputation: 2127

You can use a Hash:

def my_method(param)
 objs = {
  foo: "hey",
  bar: "ho"
 }
 objs[param]
end

Upvotes: 1

Related Questions