Posts Tagged nil
blank,empty and nil in Ruby
Object.blank?
Returns true if:
> it’s an empty array
> it’s an empty string
> !self evaluates to true
[].blank? #=> true
[1].blank? #=> false
[nil].blank? #=> false
nil.blank? #=> true
true.blank? #=> false
false.blank? #=> true
"".blank? #=> true
" ".blank? #=> true
" i ".blank? #=> false
String.empty?
"hello".empty? #=> false
"".empty? #=> true
Array.empty?
[].empty? #=> true
Hash.empty?
{}.empty? #=> true
NilClass.nil?
nil.nil? => true
Object.nil?
nil.nil? => true
.nil? => false
nil.inspect ? "nil"
Add comment April 5, 2008
Ruby nil is kicking you
Ruby is said to be a genuine Object Oriented Language. Everything is an object; even a class and moreover even nil.
Basically nil tells you about an absence of a value (or an otherwise meaningless value). n/a is a good candidate for a nil value.
The nil value is distinct from all other values. However, when we force Ruby to evaluate nil as a Boolean, it evaluates to false.
“Prayas” if nil
=> nil
“Prayas” if !nil
=> Prayas
The only values that evaluate to false Booleans are nil and false. Everything other than nil or false evaluates to true when forced into a Boolean. Zero is also evaluated as true(not as false) great!!!!
“Prayas” if false
=> nil
“Prayas” if nil
=> nil
“Prayas” if -5
=> Prayas
“Prayas” if 0
=> Prayas
nil.methods # gives you all methos
But here I am interested for methods which starts with to_. Lets gather those.
nil.methods.grep(/^to_.$/)
[”to_f”, “to_a”, “to_s”, “to_i”]
And what are they giving to me:
nil.methods.grep(/^to_.$/).each do |method_name|
puts “nil.#{method_name} :: #{nil.send(method_name).inspect}”
end
o/p
nil.to_f :: 0.0
nil.to_a :: []
nil.to_s :: “”
nil.to_i :: 0
Convert a nil value to 0 in order to avoid crash.
a = 25
b = nil
c = nil
d = “mystring”
p a||=0 # returns 25 as a is not nil
p b||=0 # returns 0 as b is nil
p c.to_i # returns 0 as nil is casted to int ,i.e other way
p d||=0 # returns “mystring” as d is not nil
so we got TWO ways to convert nil value to 0
1. using myvar ||= 0
2. using myvar.to_i OR (to_f, to_a, to_s, to_i )
How to handle when you get a crash because of nil?
def mymethod(para1)
p para1.to_s.upcase
#p para1.upcase
end
mymethod(”Prayas”)
mymethod(”Attempting”)
mymethod(nil)
o/p:
PRAYAS
ATTEMPTING
“”
The .to_s allows nil to be passed in without failure.
Without the .to_s you would receive this:(i.e if you use para1.upcase)
undefined method `upcase’ for nil:NilClass (NoMethodError)
In your views you may use something like to avoid crash
<%= @instance_name.variable_name rescue nil %>
Add comment March 22, 2008