1

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

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • `arr.blank? || arr.map { ... }` is one terser way I can think of. – Dogbert Apr 19 '15 at 10:35
  • 1
    Do we need to check `arr.blank?` condition (given `arr.class == Array`)? Doing map on blank array returns blank array. What are the benefits of checking `arr.blank?` – Utsav Kesharwani Apr 19 '15 at 10:51
  • There's something funny about this code: #map leaves the original array untouched, returning a new array which would become the result of the if statement, but the result of the if statement is not used. Did you mean `map!` instead of `map`? – Wayne Conrad Apr 19 '15 at 13:00

4 Answers4

2

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)
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • No, it does not give an error. If `arr` is `nil` it just does not do anything. Try `Array(nil).map(&:foo)` in your console. No error at all! – spickermann Apr 19 '15 at 11:53
2

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?
Community
  • 1
  • 1
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
0

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.

Endre Simo
  • 11,330
  • 2
  • 40
  • 49
0

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.

Bartosz Łęcki
  • 332
  • 2
  • 6