问题描述
|
我有str1和str2。 str1可能不是空字符串,我想构造一个数组,如:
str1 = \"\"
str2 = \"bar\"
[\"bar\"]
要么
str1 = \"foo\"
str2 = \"bar\"
[\"foo\",\"bar\"]
我现在只能想办法在两行上做到这一点,但我知道一定有一种方法可以做到这一点。
解决方法
[str1,str2].reject {|x| x==\'\'}
,在Ruby 1.9中
[*(str1 unless str1.empty?),str2]
在红宝石1.8中
[(str1 unless str1.empty?),str2].compact
,您可以使用delete_if:
[\'\',\'hola\'].delete_if(&:empty?)
如果您使用的是Rails,可以替换为空吗?用空白?
[\'\',\'hola\'].delete_if(&:blank?)
或使用一个块:
[\'\',\'hola\'].delete_if{ |x| x == \'\' }
,点击对象
[:starting_element].tap do |a|
a << true if true
a << false if false
a << :for_sure
end
# => [:starting_element,true,:for_sure]
所以一行
[].tap { |a| [foo,bar].each { |thing| a << thing unless thing.blank? } }
[bar].tap { |a| a << bar unless foo.blank? }
,另一种方式,
(str1.present? ? str1 : []) + [str2]
,也许是西里尔答案的一个更简洁的版本:
Array.new.tap do |array|
if condition
array << \"foo\"
end
end
,您可以使用三元语句:
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\"]
,my_array = [str1,str2].find_all{|item| item != \"\"}
,您可以对Aray pr Enumerable进行猴子补丁,并提供有条件的添加方法。
module Array
def add_if(object,condition=true)
self << object if condition
return self
end
end
那样,它将是可链接的,可以保留大部分空间。
array = [].add(:class,is_given?).add(object,false) #etc