Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby check if nil before calling method

Tags:

null

ruby

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 
like image 645
user1513388 Avatar asked Sep 14 '12 13:09

user1513388


People also ask

How do you check if something is nil in Ruby?

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).

How do you use nil in Ruby?

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?

Is nil the same as null Ruby?

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.

How do you return a NULL in Ruby?

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'.


1 Answers

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.

like image 182
user513951 Avatar answered Sep 28 '22 16:09

user513951