Is there a way to conditionally add an array to one row?

I have str1 and str2. str1 may or may not be an empty string, and I want to build an array like:

str1 = "" str2 = "bar" ["bar"] 

or

 str1 = "foo" str2 = "bar" ["foo", "bar"] 

I can only figure out a way to do this on two lines right now, but I know there must be a way to do this.

+6
source share
9 answers
 [str1, str2].reject {|x| x==''} 
+11
source

In ruby โ€‹โ€‹1.9

 [*(str1 unless str1.empty?), str2] 

Ruby 1.8

 [(str1 unless str1.empty?), str2].compact 
+8
source

You can use delete_if :

 ['', 'hola'].delete_if(&:empty?) 

If you use Rails, can you replace it with an empty one? on blank?

 ['', 'hola'].delete_if(&:blank?) 

or use the block:

 ['', 'hola'].delete_if{ |x| x == '' } 
+3
source

Object # tap

 [:starting_element].tap do |a| a << true if true a << false if false a << :for_sure end # => [:starting_element, true, :for_sure] 

So in one line

 [].tap { |a| [foo, bar].each { |thing| a << thing unless thing.blank? } } [bar].tap { |a| a << bar unless foo.blank? } 
+2
source

Another way,

 (str1.present? ? str1 : []) + [str2] 
+1
source

Perhaps a shorter version of Cyril's answer:

Array.new.tap do |array| if condition array << "foo" end end

+1
source

You can use the three-dimensional statement:

 ary = (str1.empty?) ? [ str2 ] : [ str1, str2 ] str1 = ''; str2 = 'bar' (str1.empty?) ? [ str2 ] : [ str1, str2 ] #=> ["bar"] str1 = 'foo'; str2 = 'bar' (str1.empty?) ? [ str2 ] : [ str1, str2 ] #=> ["foo", "bar"] 
0
source
 my_array = [str1, str2].find_all{|item| item != ""} 
0
source

You can use the Aray pr Enumerable monkey patch and provide a conditional add method.

 module Array def add_if(object, condition=true) self << object if condition return self end end 

Thus, it would be chained, retaining most of the space. array = [].add(:class, is_given?).add(object, false) #etc

0
source

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


All Articles