想象一下下面的代码:有没有比使用自定义的case语句更有用的方法来在Ruby中编写它?
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
我可以选择任何其他类,而不是,我只是用它们作为一个例子。我非常喜欢Scala的match
和提取器,我认为这可能是在Ruby中编写相同的东西的一种很好的方式。有没有更好的方式来写上述,而不必实例化新的对象,所以我可以调用他们的===
方法?
只是为了避免不必要的岗位,是的,我知道我能做到这一点:
case letter
when ["a","e","i","o","u"].include?(letter)
# ...
end
使用类方法看起来比我更好的变种很多。我不知道我们可以定义'==='来处理类作用域。 – Geo 2011-05-23 20:04:43