Reputation: 32130
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
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
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
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
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