Brandon Meredith
Brandon Meredith

Reputation: 135

Handling nil's in Ruby

I get an error when using the map method on a nil object. For example:

x = nil
x.map{ |e| e}

Is there a better way to handle this than writing:

x.map{ |e| e} unless x.nil?

(I want the output to be nil.)

Upvotes: 0

Views: 608

Answers (5)

sa77
sa77

Reputation: 3603

try this

x ? x.map {|e| e } : nil

Outputs

x = nil           # => nil
x = false         # => nil
x= ['cat', 'hat'] # => ['cat', 'hat']

Upvotes: 1

rewritten
rewritten

Reputation: 16435

I like this more than @doesterr 's solution, but it's similar:

[*x].map { |e| e }

Upvotes: 1

Matt
Matt

Reputation: 20766

Since you are using rails, you can use Object#try, which always returns nil if the object is nil:

x = [1,2,3]
x.try :map, &->(e) { e+1 }
# => [2, 3, 4]

x = nil
x.try :map, &->(e) { e+1 }
# => nil 

Upvotes: 3

falsetru
falsetru

Reputation: 368894

Using &&, the second expression will be executed unless x is nil or false.

x = nil
x && x.map { |e| e}
# => nil

Upvotes: 2

doesterr
doesterr

Reputation: 3965

Converting the nil to an Array would avoid the error, but you would end up with an empty Array instead of nil.

2.1.2 :001 > x = nil
 => nil
2.1.2 :002 > Array(x).map { |e| e }
 => []

Upvotes: 4

Related Questions