Ruby 等价于 Python 的 for/else [英] Ruby equivalent for Python's for / else

查看:48
本文介绍了Ruby 等价于 Python 的 for/else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在 Ruby 中寻找类似 Python 的 while/else 结构的东西来改进我的代码.

I've always been searching for something like Python's while / else struct in Ruby to improve my code.

这意味着循环被执行,如果循环中的条件在任何时候都不为真,则返回 else 语句中的值.

That means that the loop is executed and if the condition in the loop hasn't been true any time, then it returns the value in the else statement.

在 ruby​​ 中,我可以这样做:

In ruby, I can do like this :

if @items.empty?
  "Empty"
else
  @items.each do |item|
    item
  end
end

那么有没有办法改善这一点?

So is there a way to improve this ?

提前致谢.

推荐答案

嗯,你可以把它写成三元:

Hm, you could write it as a ternary:

@items.empty? ? 'Empty' : @items.each { |item| item }

你可能想在你的代码块中做一些更有用的事情,因为 each 是为了它的副作用而执行的,并返回原始接收者.

You may want to do something more useful in your block though, since each is executed for its side effects and returns the original receiver.

根据您的评论更新:我想您能得到的最接近的东西是

Update as per your comment: I guess the closest you could get is something like

unless @items.empty?
  @items.each { |item| p item }
else
 'Empty'
end

这篇关于Ruby 等价于 Python 的 for/else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆