ruby 语法糖:处理 nils
可能已经问过,但我找不到它..这里有两种常见情况(对我来说,在编程 Rails 时..),用 ruby 编写令人沮丧:
"a string".match(/abc(.+)abc/)[1]
在这种情况下,我收到错误,因为字符串不匹配,因此[] 运算符被调用为 nil。我想找到的是一个更好的替代方案:
temp="a string".match(/abc(.+)abc/); temp.nil? ? nil : temp[1]
简而言之,如果它不匹配,则简单地返回 nil 而不会出现错误
第二种情况是这样的:
var = something.very.long.and.tedious.to.write
var = something.other if var.nil?
在这种情况下,我只想将某些内容分配给 var 仅当它是不是零,如果是零,我会分配一些东西。其他..
有什么建议吗? 谢谢!
probably asked already but I couldn't find it.. here are 2 common situation (for me while programming rails..) that are frustrating to write in ruby:
"a string".match(/abc(.+)abc/)[1]
in this case I get an error because the string doesn't match, therefore the [] operator is called upon nil. What I'd like to find is a nicer alternative to the following:
temp="a string".match(/abc(.+)abc/); temp.nil? ? nil : temp[1]
in brief, if it didn't match simply return nil without the error
The second situation is this one:
var = something.very.long.and.tedious.to.write
var = something.other if var.nil?
In this case I want to assign something to var only if it's not nil, in case it's nil I'll assign something.other..
Any suggestion?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
忘掉 Python 返祖现象吧!
Forget that Python atavism!
并且:
请注意,
or
的运算符优先级与||
不同,对于这种用法,应首选||
。or
运算符用于流控制用途,例如ARGV[0] 或 abort('Missing parameter')
。And:
Please note that
or
has a different operator precedence than||
and||
should be preferred for this kind of usage. Theor
operator is for flow control usage, such asARGV[0] or abort('Missing parameter')
.在 Ruby on Rails 中,您可以在任何对象上使用
try
方法。根据 API:调用由符号方法标识的方法,向其传递任何参数和/或指定的块,就像常规 Ruby Object#send 一样。
然而,与该方法不同的是,如果接收对象是 nil 对象或 NilClass,则不会引发 NoMethodError 异常,并且会返回 nil。
因此,对于第一个问题,你可以这样做:
它会给你 [1] 或 nil ,不会出现错误。
In Ruby on Rails you have the
try
method available on any Object. According to the API:Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.
Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.
So for the first question you can do this:
And it will either give you [1] or nil without error.
首先,我推荐 ick 的
maybe
(相当于 andand)我不确定我是否理解第二个,你想要这个吗?
For the first I'd recommend ick's
maybe
(equivalent to andand)I am not sure I understand the second one, you want this?
NilClass#to_a
返回一个空数组,在其外部进行索引会为您提供nil
值。或者(我所做的)你可以打火柴:
NilClass#to_a
returns an empty array, and indexing outside of it gives younil
values.Alternatively (what I do) you can splat the matches:
对于第一个问题,我认为鲍勃的回答很好。
对于第二个问题,
For the first question, I think Bob's answer is good.
For the second question,