如何在 Ruby 中的 1 行中执行多个连续的函数?
我有两个具有相同条件的后续函数,我想知道编写此函数的最佳方法是什么?我知道执行此操作的一种方法是使用 if (condition) ... end,但我想知道是否可以像 bash 那样在一行中执行此操作, '[$n == $value] echo "$n “&&休息'。
n = 0
loop do
puts n if n == value # puts and break is having the same condition, but
break if n == value # can we do it in one line?
n += 1
end
I have two succeeding function with the same condition and I wonder what is the best way to write this? I know the one way to do this is using if (condition) ... end, but I'm wondering if I can do it in one-line similar to bash, '[$n == $value] echo "$n" && break'.
n = 0
loop do
puts n if n == value # puts and break is having the same condition, but
break if n == value # can we do it in one line?
n += 1
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为 n 为真,所以您可以使用“and”连接符。它读起来非常好:
--edit--
正如评论中指出的,这实际上行不通,因为 put 返回 nil,这是不真实的。我的不好。您可以使用“或”来代替,但这读起来不太好。所以我想说只需用括号将语句分组即可。
您还可以更改 put 方法以返回它打印的值,这可以与“and”一起使用,但这可能不是最聪明的想法:)
我猜您的实际代码与您粘贴的代码不同,所以如果链中的第一个方法返回一些内容,您可以使用“and”。
Because n is truthy, you can use the 'and' joiner. It reads really nicely:
--edit--
As pointed out in comments, that won't actually work because puts returns nil, which isn't truthy. My bad. You can use 'or' instead, but that doesn't read nicely. So I'd say just group the statements with parenthesis.
You could also change the puts method to return the value it prints, and that would work with 'and', but that's probably not the smartest idea :)
I'm guessing your actual code is different to what you've pasted, so if the first method in your chain returns something, you can use 'and'.
一种简单的方法是只将语句放在括号中:
如果放在括号中有点太多,则开始-结束即可解决问题:
输出:
One easy way is to just parenthesize the statements:
If it's a bit much to put in parentheses, a begin-end will do the trick:
Output:
proc { 放置 n;休息; }.() 如果 n == 3
proc { puts n; break; }.() if n == 3
Ruby 的黄金法则之一是,如果您正在编写循环,那么您可能会做错。在这种特殊情况下,循环所做的就是在集合中查找元素。在 Ruby 中,已经有一种在集合中查找元素的方法:
Enumerable#find
。无需自己编写。因此,代码被简化为:
现在我们对问题有了一个很好的声明式表述,很容易看出(假设
value.to_s
具有合理的相等语义和合理的语义),这正是等同于:因此,整个循环从一开始就完全没有必要。
One of the golden rules of Ruby is that if you are writing a loop, you are probably doing it wrong. In this particular case, all that your loop is doing is to find an element in a collection. In Ruby, there already is a method for finding an element in a collection:
Enumerable#find
. There is no need to write your own.So, the code gets simplified to:
Now that we have a nice declarative formulation of the problem, it is easy to see that (assuming sane equality semantics and sane semantics of
value.to_s
), this is exactly the same as:So, the whole loop was completely unnecessary to begin with.