想象一下下面的代码:
class SimpleLetter
def values
("a" .. "z").to_a
end
def ===(other)
values.include?(other)
end
end
class Vowel < SimpleLetter
def values
["a","e","i","o","u"]
end
end
class Consonant < SimpleLetter
def values
super - Vowel.new.values
end
end
objects = ("a" .. "f").to_a + (1 .. 5).to_a
objects.each do |letter|
case letter
when Vowel.new
puts "#{letter} it's a vowel"
when Consonant.new
puts "#{letter} it's a consonant"
else
puts "#{letter} it's something else"
end
end
我本可以选择任何其他类(class),我只是以它们为例。我非常喜欢 Scala 的 match
和提取器,我认为这可能是用 Ruby 编写相同内容的好方法。有没有更好的方法来编写上面的代码而不必实例化新对象以便我可以调用它们的 ===
方法?
为了避免不必要的帖子,是的,我知道我可以这样做:
case letter
when ["a","e","i","o","u"].include?(letter)
# ...
end
最佳答案
你不需要角色的类。将它们设置为数组,并在 case 语句中使用 splat 运算符。
SimpleLetter = ("a" .. "z").to_a
Vowel = %w[a e i o u]
Consonant = SimpleLetter - Vowel
(("a" .. "f").to_a + (1 .. 5).to_a).each do |letter|
case letter
when *Vowel
puts "#{letter} it's a vowel"
when *Consonant
puts "#{letter} it's a consonant"
else
puts "#{letter} it's something else"
end
end
关于ruby - 有没有比使用自定义 case 语句更实用的方法来用 Ruby 编写这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6101716/