Jeff Zivkovic
Jeff Zivkovic

Reputation: 587

Get param value dynamically

My question model holds the prompt and the answer choices for questions that students can answer. It includes columns named :choice_0, :choice_1, :choice_2, :choice_3, :choice_4, and :choice_5.

In one section of my controller, I've used the following code:

correct_array.push(these_params[:choice_0]) if !these_params[:choice_0].blank?
correct_array.push(these_params[:choice_1]) if !these_params[:choice_1].blank?
correct_array.push(these_params[:choice_2]) if !these_params[:choice_2].blank?
correct_array.push(these_params[:choice_3]) if !these_params[:choice_3].blank?
correct_array.push(these_params[:choice_4]) if !these_params[:choice_4].blank?
correct_array.push(these_params[:choice_5]) if !these_params[:choice_5].blank?

In other areas of my app, I've used the #{} syntax, for example:

params[:choice_#{n}]

But that doesn't work within a params hash for some reason. I'm sure that there is a drier way to accomplish these five lines.

Thank you in advance for any insight.

Upvotes: 0

Views: 57

Answers (2)

moveson
moveson

Reputation: 5213

A more Ruby way to do this is:

correct_array = (0..5).map { |i| these_params["choice_#{i}".to_sym] }.select(&:present?)

Or as a method:

def correct_array
  (0..5).map { |i| these_params["choice_#{i}".to_sym] }.select(&:present?)
end

In either case, you have the added bonus of not having to initialize correct_array as it is created on the fly.

Upvotes: 1

Fangxing
Fangxing

Reputation: 6105

You may try this

(0..5).each do |i|
  param_i = these_params["choice_#{i}".to_sym]
  correct_array.push(param_i) if param_i.present?
end

Upvotes: 1

Related Questions