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
However if the string is empty nil
I get the following error.
NoMethodError: undefined method `strip' for nil:NilClass
I'm using Ruby 1.9 so whats the easiest way to check if the value is nil
before calling the strip method?
Update:
I tried this on an element in an array but got the same problem:
data[2][1][6].nil? ? data[2][1][6] : data[2][1][6].split(":")[1].strip
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void. Ruby also provide a nil?
nil is an Object, NULL is a memory pointer Sadly, when this happens, Ruby developers are confusing a simple little Ruby object for something that's usually radically different in “blub” language. Often, this other thing is a memory pointer, sometimes called NULL, which traditionally has the value 0.
No, you can't return nothing. In ruby you always return something (even if it's just nil ) - no way around that. That said, nil is supposed to represent the concept of 'nothing'.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With