I have a string in Ruby on which I\'m calling the strip method to remove the leading and trailing whitespace. e.g.
s = \"12345 \"
s.strip
H
Method which works for me (I know, I should never pollute pristine Object
space, but it's so convenient that I will take a risk):
class Object
def unless_nil(default = nil, &block)
nil? ? default : block[self]
end
end
p "123".unless_nil(&:length) #=> 3
p nil.unless_nil("-", &:length) #=> "-"
In your particular case it could be:
data[2][1][6].unless_nil { |x| x.split(":")[1].unless_nil(&:strip) }
To complete the options shown here, there is the "Existence Check Shorthand", recommended in the Ruby Style Guide:
Use
&&=
to preprocess variables that may or may not exist. Using&&=
will change the value only if it exists [means, is notnil
], removing the need to check its existence withif
.
So in your case you would do:
s = "12345 "
s &&= s.strip
Ruby 2.3.0 added a safe navigation operator (&.
) that checks for nil before calling a method.
s&.strip
If s
is nil
, this expressions returns nil
instead of raising NoMethodError
.
You could simply do this
s.try(:strip)
ActiveSupport
comes with a method for that : try
. For example, an_object.try :strip
will return nil
if an_object
is nil, but will proceed otherwise. The syntax is the same as send
. Cf active_support_core_extensions.html#try.