在 Ruby 中处理这种类型的包容性逻辑的最佳方法是什么?
在 Ruby 中是否有更好的方法来处理这个问题,同时继续使用符号?
pos = :pos1 # can be :pos2, :pos3, etc.
if pos == :pos1 || pos == :pos2 || pos == :pos3
puts 'a'
end
if pos == :pos1 || pos == :pos2
puts 'b'
end
if pos == :pos1
puts 'c'
end
最明显的方法是将符号替换为数字常量,但这不是一个选择。
pos = 3
if pos >= 1
puts 'a'
end
if pos >= 2
puts 'b'
end
if pos >= 3
puts 'c'
end
谢谢。
编辑 我刚刚发现 Ruby 按 alpha/num 顺序对符号进行排序。这非常有效。
pos = :pos2 # can be :pos2, :pos3, etc.
if pos >= :pos1
puts 'a'
end
if pos >= :pos2
puts 'b'
end
if pos >= :pos3
puts 'c'
end
Is there a better way of handling this in Ruby, while continuing to use the symbols?
pos = :pos1 # can be :pos2, :pos3, etc.
if pos == :pos1 || pos == :pos2 || pos == :pos3
puts 'a'
end
if pos == :pos1 || pos == :pos2
puts 'b'
end
if pos == :pos1
puts 'c'
end
The obvious way would be swapping out the symbols for number constants, but that's not an option.
pos = 3
if pos >= 1
puts 'a'
end
if pos >= 2
puts 'b'
end
if pos >= 3
puts 'c'
end
Thanks.
EDIT
I just figured out that Ruby orders symbols in alpha/num order. This works perfectly.
pos = :pos2 # can be :pos2, :pos3, etc.
if pos >= :pos1
puts 'a'
end
if pos >= :pos2
puts 'b'
end
if pos >= :pos3
puts 'c'
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不确定这是否是最好的方法……
我会使用数组中的
include?
方法:Not sure if this is the best way......
I would make use of the
include?
method from array:只需使用
case
语句Just use the
case
statement有很多不同的方法来获取输出。你是哪一个
想要取决于您对
if
语句的具体反对意见。我添加了一些额外的格式以使输出更容易
阅读。
如果您不喜欢逻辑或以及它们如何分隔结果
从输出中,您可以使用查找表:
或者,如果您想要查找表中的所有“工作”:
如果您的问题是符号不是序数,那么您可以
通过将它们转换为字符串来对它们进行排序:
或者您可以将比较运算符修补到符号中
类(不推荐):
或者您可以使用查找表来提供序数值:
这些是我脑海中显而易见的值。如果没有更多具体说明您的
if
方法的问题是什么,很难说什么是最好的;你的第二个例子表明你真正想要的是一种将符号变成序数的方法。There are lots of different ways to get your output. Which one you
want depends on your specific objections to your
if
statements.I've added a bunch of extra formatting to make the output easier
to read.
If you don't like the logical ORs and how they separate the results
from the output, you can use a lookup table:
Or, if you want all the "work" in the lookup table:
If your problem is that symbols aren't ordinals, then you can
ordinalize them by converting them to strings:
Or you could monkey patch a comparison operator into the Symbol
class (not recommended):
Or you could use a lookup table to supply your ordinal values:
Those are the obvious ones off the top of my head. It is hard to say what would be best without more specifics on what your problem with your
if
approach is; your second example indicates that what you really want is a way to make symbols into ordinals.更一般地,您可以使用这个:
或者对于您的具体示例:
More generically, you can use this:
Or this, for your specific example: