Hi all,
In some use cases where the result of a call could be nil but expect an
object that responds to “[]”(via duck typing) we receive the following
error:
as an example:
a = ‘"(xxxx,yyyy)"’
/.?"(.?)"/i.match(a)[1] => “xxxx,yyyy”
if a == nil or a doesn’t match the regular expression,
I receive the error:
undefined method `[]’ for nil:NilClass (NoMethodError)
that kind of situations make you have to check all the time for
the obj#nil? return of any process
I solved with ruby magic:
class NilClass
def
nil
end
end
In that way whenever you do something like:
nil[] => nil
nil[1234] => nil
nil[1,2,3,4] => nil
nil[“xxxx”] => nil
will allways return nil without giving an undefined method ‘[]’
My question is:
Wouldn’t be this solution a good idea for implementing it in the base
ruby
NilClass?
I’m fine with adding that code snippet at the beginning of any library,
though.
I’m just thinking in loud voice and realtively noob to Ruby.
Regards to all
Eduardo B.
Eduardo B. wrote in post #1005707:
My question is:
Wouldn’t be this solution a good idea for implementing it in the base
ruby
NilClass?
In a word: No.
The trouble is, often this is the sign of an error, and if I write foo[]
I want to be told the line where foo had the wrong value. If you don’t
do this then my code may fail 10 or 100 lines later with some strange
error, probably about something else being nil, and I’d have very little
insight into how it got like that.
Note that you don’t have to use ‘nil?’ tests, there are much less
verbose ways of doing this in ruby. Any value (object) other than false
or nil is true. So there are all sorts of permutations:
foo[x] if foo
foo && foo[x]
foo ? foo[x] : “error”
(foo || [])[x]
return unless foo
foo[x]
And quite a few variants for your particular problem, e.g.
if /((.*))/ =~ foo
puts $1
end
I’m fine with adding that code snippet at the beginning of any library,
though.
It’s generally frowned upon to pollute the global core objects, but this
one probably isn’t going to do much harm, especially if this is just
code for your own use.
Regards,
Brian.
Thank you Brian for the answer,
I can see the problem,
Tahnk you again for the insight…
Eduardo