有没有办法在一行中有条件地添加数组?

Jer*_*ith 9 ruby ruby-on-rails

我有str1和str2.str1可能是或不是一个空字符串,我想构建一个数组,如:

str1 = ""
str2 = "bar"
["bar"]
Run Code Online (Sandbox Code Playgroud)

要么

str1 = "foo"
str2 = "bar"
["foo", "bar"]
Run Code Online (Sandbox Code Playgroud)

我现在只能想办法在两条线上做这个,但我知道必须有办法做到这一点.

saw*_*awa 15

在红宝石1.9

[*(str1 unless str1.empty?), str2]
Run Code Online (Sandbox Code Playgroud)

在红宝石1.8

[(str1 unless str1.empty?), str2].compact
Run Code Online (Sandbox Code Playgroud)

  • 干净整洁.绝对是我最喜欢的答案! (2认同)

mae*_*ics 14

[str1, str2].reject {|x| x==''}
Run Code Online (Sandbox Code Playgroud)

  • 或者:[str1,str2] .reject(&:empty?) (9认同)

Cyr*_*ris 5

对象#tap

[:starting_element].tap do |a|
  a << true if true
  a << false if false
  a << :for_sure
end
# => [:starting_element, true, :for_sure]
Run Code Online (Sandbox Code Playgroud)

所以在一行

[].tap { |a| [foo, bar].each { |thing| a << thing unless thing.blank? } }
[bar].tap { |a| a << bar unless foo.blank? }
Run Code Online (Sandbox Code Playgroud)