在Ruby中使用块设置变量 [英] Setting variables with blocks in ruby

查看:44
本文介绍了在Ruby中使用块设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己在Ruby中经常使用类似PHP的循环,而当其余语言如此简洁时,这感觉很不对劲.我结束了这样的代码:

I find myself using PHP-like loops a lot in Ruby and it feels wrong when the rest of the language is so neat. I wind up with code like this:

conditions_string = ''

zips.each_with_index do |zip, i|

    conditions_string << ' OR ' if i > 0
    conditions_string << "npa = ?"

end

# Now I can do something with conditions string

我觉得我应该能够做这样的事情

I feel like I should be able to do something like this

conditions_string = zips.each_with_index do |zip, i|

    << ' OR ' if i > 0
    << "npa = ?"

end

在Ruby中是否有一种整洁"的方法来设置带有块的变量?

Is there a 'Neat' way to set a variable with a block in Ruby?

推荐答案

您似乎没有在循环中访问 zip ,因此以下操作应该有效:

You don't seem to be accessing zip in your loop, so the following should work:

conditions_string = (['npa = ?'] * zips.length).join(' OR ')

如果您需要访问 zip ,则可以使用:

If you need access to zip, then you could use:

conditions_string = zips.collect {|zip| 'npa = ?'}.join(' OR ')

这篇关于在Ruby中使用块设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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