How would you implement this idiom in ruby?

As someone who came from a Java background and being new to Ruby, I was wondering if there is an easy way to do this with ruby.

new_values = foo(bar) if new_values if arr arr << new_values else arr = new_values end end 
+4
source share
5 answers

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

 arr ||= [] arr << new_values 

If you do this in a loop or some similar case, there may be more idiomatic ways to do this. For example, if you repeat the list, passing each foo() value and creating an array of results, you can simply use:

 arr = bars.map {|bar| foo(bar) } 
+7
source

If I understand 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 add the entire array of values ​​to the end of the array as one nested entry.

+3
source

arr = [*arr.to_a + [*new_values.to_a]]


Start with:

 arr ||= [] 

And then, depending on whether new_values array or not

 arr += new_values # if array arr << new_values # if not arr += [*new_values] # if it could be either 

In addition, you can get rid of the test for new_values , taking advantage of the fact that NilClass implements the .to_a => [] method and reduces everything to:

 arry ||= [] arr += [*new_values.to_a] 

But wait, we can use this trick again and turn everything into a one-liner:


 arr = [*arr.to_a + [*new_values.to_a]] 

+3
source

I am not going to write an indescribable single-line font, but I think this is perfectly clear. Assuming, like Frogs, what you really need is an extension (concat):

 arr = (arr || []).concat(foo(bar) || []) 

Or:

 (arr ||= []).concat(foo(bar) || []) 
+1
source

I would use:

 new_values = foo(bar) arr ||= [] arr << new_values if new_values 
0
source

Source: https://habr.com/ru/post/1337398/


All Articles