有没有比使用自定义 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
Imagine the following code:
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
I could have chosen any other classes instead, I am just using them as an example. I like Scala's match
and extractors a lot, and I figured this could be a nice way of writing the same thing in Ruby. Is there a better way of writing the above without having to instantiate new objects just so I could call their ===
method?
Just to avoid unnecessary posts, yes, I know I could do this:
case letter
when ["a","e","i","o","u"].include?(letter)
# ...
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不需要为角色上课。将它们设置为数组,并在 case 语句中使用 splat 运算符。
You don't need classes for the characters. Set them as arrays, and use the splat operator in the case statement.
===
也适用于块:===
works on blocks, too:您可以使用类方法而不是实例方法:
You could use class methods instead of instance methods:
你让我困惑的代码,因为
SimpleLetter
应该是单个字母,而不是整个字母表。尽管猴子补丁有点冒险,但我很想执行以下操作:
The code you have confused me, because
SimpleLetter
should be a single letter, rather than the whole alphabet.I'd be half tempted to do the following, although monkeypatching is a bit risky:
您已经有了几个很好的答案(例如sawa 的答案),因此我提供了一个只是为了好玩而没有
case
语句的答案:输出:
多图和字符文字仅在 1.9 中有效。
You already have several good answers (e.g. sawa's), so I'm including a just for fun one without a
case
statement:Output:
The multi-splat and character literals only work in 1.9.