红宝石句法糖:处理零食 [英] ruby syntactic sugar: dealing with nils
问题描述
可能已经问过了,但我找不到它..这是2种常见的情况(对我来说是在编程rails ..时),这令人沮丧地用ruby编写:
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]
在这种情况下,由于字符串不匹配,我得到一个错误,因此[]运算符在nil时被调用.我想找到的是以下更好的替代方法:
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]
简而言之,如果不匹配,只需返回nil即可,没有错误
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?
在这种情况下,我只想为var分配一些东西,如果它不是nil,我要分配一些东西.other..
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..
有什么建议吗?谢谢!
推荐答案
For the first I'd recommend ick's maybe
(equivalent to andand)
"a string".match(/abc(.+)abc/).maybe[1]
我不确定我是否理解第二个,你想要这个吗?
I am not sure I understand the second one, you want this?
var = something.very.long.and.tedious.to.write || something.other
这篇关于红宝石句法糖:处理零食的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!