有没有办法在 Ruby 中测试 3
在 ruby 中,有一种方法可以执行以下操作
20.times do |n|
if 3 < n < 10
id = 40555
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web
技术交流群。
在 ruby 中,有一种方法可以执行以下操作
20.times do |n|
if 3 < n < 10
id = 40555
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用两种比较:
或者您可以使用
Between :
或者您可以使用范围和
cover?(1.9)或
include?( 1.8) 方法:
请注意,最后两个包括端点。不过,范围可以选择排除其端点。
顺便说一句,在代码审查中,我会将像 3 和 10 这样的“神奇数字”标记为需要重构为适当命名的自记录方法,例如
if inside_tolerance?(n)
或类似的。You can use two comparisons:
or you can use
between
:or you can use a range and the
cover?
(1.9) orinclude?
(1.8) methods:Note though that the last two include the endpoints. A range can optionally exclude its endpoint though.
BTW, in a code review I'd flag "magic numbers" like the 3 and 10 as something that needs to be refactored into an appropriately named, self-documenting method, something like
if within_tolerance?(n)
or similar.(感谢谦虚的 Comparable 模块)
(Thanks to the humble Comparable module)
探究各种实现的速度始终是一个很好的练习。
为了欢乐,我将评论中的建议代码添加到OP的问题中,这让我感到惊讶。我没想到测试中的改变会提高速度,但它确实产生了微小的差异。为了理解为什么我添加了空格,以防万一这是一个行解析问题,而我认为不会是这样。并且,为了排除它是
and
与&&
运算符,我添加了这些。一般来说,添加的空格不会产生任何影响,这正是我所期望的。微小的差异可能是由于我的机器上的一些工作被解雇了。
It's always a good exercise to poke at the speed of various implementations.
For jollies I added the suggested code from the comment to the OP's question, which surprised me. I wouldn't have expected the change in the test to improve the speed, but it does make a minor difference. To understand why I added spaces, in case it was a line parsing issue, which I didn't think it would be. And, to rule out it was the
and
vs.&&
operators I added those.In general the added spaces don't make a difference which is what I expected. The minor variance is probably due to some job firing on my machine.
不像 3 到 10 那样清晰,但仍然很小。
Not as clear as between 3 and 10 but still minimal.