Ruby Syntactic Sugar: Nile Processing

may have already asked, but I could not find it .. here are 2 common situations (for me, when I programmed the rails ..) that upset me to write in ruby:

"a string".match(/abc(.+)abc/)[1]

in this case, I get an error because the string does not match, so the [] operator is called in nil. What I would like to find is a nicer alternative to the following:

temp="a string".match(/abc(.+)abc/); temp.nil? ? nil : temp[1]

in short, if it did not match just return nil without error

The second situation is as follows:

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 is not nil, in case it is nil, I will assign something.other ..

Any suggestion? Thank!

+5
source share
6 answers

ick maybe ( andand)

"a string".match(/abc(.+)abc/).maybe[1]

, , ?

var = something.very.long.and.tedious.to.write || something.other
0

Ruby on Rails try, . API:

, , / , , Ruby Object # send.

, NoMethodError , nil, nil NilClass.

, :

"a string".match(/abc(.+)abc/).try(:[], 1)

[1], nil .

+3
"a string"[/abc(.+)abc/, 1]
# => nil
"abc123abc"[/abc(.+)abc/, 1]
# => "123"

var = something.very.long.and.tedious.to.write || something.other

, or , || || . or , ARGV[0] or abort('Missing parameter').

+3

Python!

"a string"[/abc(.+)abc/,1] # => nil
+3
"a string".match(/foo(bar)/).to_a[1]

NilClass#to_a , nil.

( ) :

_, some, more = "a string".match(/foo(bar)(jim)/).to_a
0

, , .

var = something.very.long.and.tedious.to.write.instance_eval{nil? ? something.other : self}
0

All Articles