Reputation: 135
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
Reputation: 3603
try this
x ? x.map {|e| e } : nil
Outputs
x = nil # => nil
x = false # => nil
x= ['cat', 'hat'] # => ['cat', 'hat']
Upvotes: 1
Reputation: 16435
I like this more than @doesterr 's solution, but it's similar:
[*x].map { |e| e }
Upvotes: 1
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
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
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