mariovzc
mariovzc

Reputation: 213

Assign a function to a variable with conditional (ruby)

Well I have a question object that as you can see it receives parameters true / false, what I would like is that in the variable question_type given the value of questions[:q1] it is assigned one of the functions question_type_true or question_type_false to be able to execute it within the each.

questions = {
  q1: true,
  q3: true,
  q4: true,
  q5: true,
  q6: true,
  q7: true,
  q8: true
}

question_type = questions[:q1] == true ? question_type_true : question_type_false

questions.each do |key, value|
  question_type(value)
end


def question_type_true(question)
  p "true function #{question}"
end

def question_type_false(question)
  p "false function #{question}"
end

example:

questions = { q1: false, q3: true, q4: true}

output:

p "true function false"
p "true function true"
p "true function true

Upvotes: 1

Views: 1426

Answers (2)

Simple Lime
Simple Lime

Reputation: 11050

You can call Object#method to get a reference to a Method and then call it:

question_type = questions[:q1] == true ? method(:question_type_true) : method(:question_type_false)

questions.each do |key, value|
  question_type.call(value)
end

Note that you will need to have defined the methods before you can call method to retrieve it:

# works:
def some_method; end
method(:some_method)

# undefined method error:
method(:some_method)
def some_method; end

so you'll need to move your method definitions to the top of the example given.

If the method you need is an instance method on something, you can access it by calling method on the instance:

o = Object.new
o.method(:nil?)

and similarly if it's a class method:

Object.method(:new)

Upvotes: 2

Max
Max

Reputation: 22365

You just store the name of the method as a symbol

question_type = questions[:q1] ? :question_type_true : :question_type_false

Then send the symbol to the object you want the method to run on:

questions.each do |key, value|
  send question_type, value
end

Upvotes: 2

Related Questions