I\'m just breaking into the ruby world and I could use a helping hand.
Suppose b
is nil
.
I\'d like the following code to return n
Remark in advance: b
is a method, not a variable. So b 'is' not nil, it returns nil.
When 'b' is a method, why not modify b, so it returns something, what can handle nil.
See below for an example.
You may define the missing methods:
class A
def b
nil
end
end
class NilClass
def c(p);nil;end
def e;nil;end
end
a = A.new
a.b.c("d").e
But I think, a rescue may fit your need better:
class A
def b
nil
end
end
a = A.new
x = begin a.c.c("d").e
rescue NoMethodError
nil
end
An example, how you may define a nil-like example.
class A
def b
MyNil.new
end
end
class MyNil
def method_missing(m, *args, &block)
if nil.respond_to?(m)
nil.send(m)
else
self
end
end
#Simulate nils bahaviour.
def nil?;true;end
def inspect;nil.inspect;end
def to_s;nil;end
end
a = A.new
x = a.b.c("d").e
p x
puts x
p x.nil?