我有str1和str2。str1可能是空字符串,也可能不是,我想构造一个数组,如下所示:
str1 = ""
str2 = "bar"
["bar"]或
str1 = "foo"
str2 = "bar"
["foo", "bar"]我现在只能想出两行代码来做这件事,但我知道肯定有一种方法。
发布于 2011-05-20 06:22:37
[str1, str2].reject {|x| x==''}发布于 2011-05-20 06:31:56
在ruby 1.9中
[*(str1 unless str1.empty?), str2]ruby 1.8
[(str1 unless str1.empty?), str2].compact发布于 2016-04-18 02:49:41
Object#tap
[: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? }https://stackoverflow.com/questions/6065450
复制相似问题