2017-02-02 10 views
0

Учитывая следующие поля:Как динамически генерировать строку на основе предоставленных переменных?

Desk.red (true,false) 
Desk.blue (true,false) 
Desk.green (true,false) 
Desk.purple (true,false) 
Desk.orange (true,false) 

Можно ли создать вспомогательный метод, как так:

def desk_color_option_string(red,blue,green,purple,orange) 
    sentence = "The desk is available in the color" 
return sentence 

Где данный варианты, как так:

(true, false, false, false, false) 
(true, true, true, false, false) 
(true, true, true, true, true) 

Метод возвращает

The desk is available in the color red. 
The desk is available in the color red, blue, and green 
The desk is available in the color red, blue, green, purple and orange. 

Благодаря

ответ

2

Вы можете поместить имена цветов в массив, или пройти в массиве цветов, а затем использовать to_sentence:

def desk_color_option_string(red,blue,green,purple,orange) 
    colors = method(__method__).parameters.map{ |arg| arg[1] if eval(arg[1].to_s)}.delete_if{ |arg| arg == nil} 
    "The desk is available in the color #{colors.to_sentence}." 
end 
#=> The desk is available in the color red, blue and green. 
+0

Это возвращается «правда, правда, правда, и ложь» – AnApprentice

+1

Обновлено получить имена цветов – Shannon

+0

Спасибо, но что теперь вернуться «На рабочем столе доступный в цвете красный, синий, зеленый, фиолетовый и оранжевый. " кажется, что истина истинна или ложна. Он должен был вернуть «Рабочий стол доступен в цвете» Красный, синий и зеленый » – AnApprentice

-1

Да, вы можете создать helper_method.

В Просмотр:

<p><%= desk_color_option_string(true, true, true, false, false) %></p> 

В Helper:

def desk_color_option_string(red,blue,green,purple,orange) 
    sentence = "The desk is available in the color " + method(__method__).parameters.map{|p| p[1] if eval(p[1].to_s)}.delete_if{|n| n==nil}.to_sentence 
    return sentence 
    # "The desk is available in the color red, blue and green" 
end 
+0

Это вернулось «true, true, true и false». – AnApprentice

+0

ответ обновлен. – Emu

0

Хороший и полностью динамический способ будет использовать хэш. Таким образом, вам не нужно запоминать порядок параметров. Кроме того, наличие более 2-3 параметров является плохой практикой.

def desk_color_option_string(colors = {}) 
    "The desk is available in the color #{colors.select{|k,v|v}.keys.to_sentence}." 
end 

Это даст вам результат в соответствии с хешем, который вы пройдете.

desk_color_option_string({red: true, blue: true, green: false}) 
#=> "The desk is available in the color red and blue." 

или просто передать цвета, которые вы хотите в строке

desk_color_option_string({red: true, blue: true, green: true}) 
#=> "The desk is available in the color red, blue, and green." 
Смежные вопросы