如何根据提供的变量动态生成字符串?

时间:2017-02-02 04:08:18

标签: ruby-on-rails ruby ruby-on-rails-4

给出以下字段:

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.

由于

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

一种好的,完全动态的方法是使用哈希。这样你就不需要记住params的顺序了。此外,超过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."

答案 2 :(得分:-1)

是的,您可以生成一个helper_method。

查看

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

帮助

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