Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you implement this idiom in ruby?

Tags:

ruby

As someone who came from Java background and being a newbie to Ruby, I was wondering if there is a simple way of doing this with ruby.

new_values = foo(bar)
if new_values
  if arr
    arr << new_values
  else 
    arr = new_values
  end
end
like image 680
truthSeekr Avatar asked Dec 09 '22 11:12

truthSeekr


2 Answers

Assuming "arr" is either an array or nil, I would use:

arr ||= []
arr << new_values

If you're doing this in a loop or some such, there might be more idiomatic ways to do it. For example, if you're iterating a list, passing each value to foo(), and constructing an array of results, you could just use:

arr = bars.map {|bar| foo(bar) }
like image 123
Chris Heald Avatar answered Dec 12 '22 01:12

Chris Heald


If I'm understanding you correctly, I would probably do:

# Start with an empty array if it hasn't already been set
@arr ||= []

# Add the values to the array as elements
@arr.concat foo(bar)

If you use @arr << values you are adding the entire array of values to the end of the array as a single nested entry.

like image 24
Phrogz Avatar answered Dec 12 '22 00:12

Phrogz