1

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
1
  • Your output does not match your code? the example shows questions[:q1] == false which would result in the usage of the question_type_false method not the question_type_true method as your output suggests Commented Mar 23, 2018 at 20:49

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.