我试图为我的应用程序实现一个元素,但无法解决如何减少if语句的数量问题。我实现了以下工作,但if语句的数量是荒谬的。更不用说我必须为" x"。
以外的变量重复相同的代码if x.color includes "red"
print "red"
elsif x.color includes "blue"
print "blue"
elsif x.color includes "yellow"
print "yellow"
elsif x.color includes "red" and "blue"
print "red and blue"
...
...
elsif x.color includes "red" and "blue" and "yellow"
print "red and blue and yellow"
else
print "none"
end
有没有办法用较少的代码来解释所有条件?
非常感谢你的时间!
答案 0 :(得分:2)
colors = %w[red blue yellow].select { |color| x.color.include?(color) }
print colors.count.zero? ? 'none' : colors.join(' and ')
答案 1 :(得分:1)
如果您希望x.colors中的颜色多于红色和黄色。你可以先做&使用此数组输入,然后使用和。
连接它common_colors = x.colors & %w(red blue yellow)
unless common_colors.empty?
puts colors.join(" and ")
else
puts "none"
end
此外,您无需重复所有颜色即可。您可以对它们使用迭代。假设您有3个变量x,y和z。
[x, y, z].each do |var|
common_colors = var.colors & %w(red blue yellow)
unless common_colors.empty?
puts colors.join(" and ")
else
puts "none"
end
end
答案 2 :(得分:0)
我的2美分是,每当在Ruby中编写任何可重用的东西时,你都应该采用OOP方式。在您的情况下,可能的解决方案之一是:
class X
class Color < String
VALID = "red", "blue", "yellow"
def self.new color
fail TypeError, "Invalid color: #{color}!" unless VALID.include? color
super
end
end
attr_reader :color
def initialize *colors
@color = colors.map { |c| Color.new c }.uniq.sort # Turn them into Color objects.
end
def present_yourself
puts "I'm #{color_string}."
end
private
# This method is the remnant of your if statements. I made it private just to demonstrate
# that you can (and should) hide the engines from the object user.
#
def color_string
return "colorless" if color.empty? # No color case.
return color[0] if color.size == 1 # Single color case.
# Two or more colors case:
color.tap { |*colors, color| return colors.join( ", " ) + " and " + color }
end
end
这个小基础设施很容易重构,让你可以做你想做的事情,而不必关心它是如何完成的:
x = X.new
x.present_yourself
#=> I'm colorless.
x = X.new "red", "blue", "yellow"
x.present_yourself
#=> I'm blue, red and yellow.
x = X.new "red", "blue", "foobar"
#=> TypeError: Invalid color: foobar!