Nick Ginanto
Nick Ginanto

Reputation: 32130

Enumerating empty/nil, the Ruby way

Is there a Rubier way to do

if !arr.blank?
  arr.map{|x| x.do_something}
end

for empty arrays in Ruby, and empty relations in Rails

Upvotes: 1

Views: 1316

Answers (4)

Andrey Deineko
Andrey Deineko

Reputation: 52357

You can shorten it to one line using unless. Also use Symbol#to_proc instead of explicit block:

arr.map(&:do_something) unless arr.blank?

Upvotes: 2

Bartosz Łęcki
Bartosz Łęcki

Reputation: 342

So if you have an array which may have nil values you can just use Array#compact which return array without nil values.

2.2.0 :013 > arr = [1, nil, "2"]
2.2.0 :014 > arr.compact
 => [1, "2"] 

If the array is empty #map method won't have any side effects so you are safe and you don't have to check if array is empty.

Upvotes: 0

Endre Simo
Endre Simo

Reputation: 11551

It's a good practice to avoid negative logic for a condition determination if possible. So instead of

if !arr.blank?
  arr.map{|x| x.do_something}
end

you can write

if arr.present?
  arr.map{|x| x.do_something}
end

Inclusion is always a faster operation than exclusion.

Upvotes: 0

spickermann
spickermann

Reputation: 106932

You would use this for arrays that might be empty or even nil:

Array(arr).map(&:do_something)

For relations in Rails it is just the following, because Rails' relations do not return nil:

relation.map(&:do_something)

Upvotes: 2

Related Questions