0

配列を反復処理し、1つの基準に基づいてその要素を変更し、最後の要素の後を除いて、各要素の後に別の要素を挿入したいと思います。これを行うための最もRubyの慣用的な方法は何でしょうか?

def transform(input)
  words = input.split
  words.collect {|w|
    if w == "case1"
      "add that"
    else
      "add these" + w
    end
    # plus insert "x" after every element, but not after the last
  }
end

例:

transform("Hello case1 world!") => ["add theseHello", "x", "add that", "x", "add theseworld!"]
4

2 に答える 2

0
def transform input
  input.split.map do |w|
    [
      if w == 'case1'
        'add that'
      else
        'add these' + w
      end,
      'x'
    ]
  end.flatten[0..-2]
end

これは多くの場合、次のように記述されます。

def transform input
  input.split.map do |w|
    [ w == 'case1' ? 'add that' : 'add these' + w, 'x' ]
  end.flatten[0..-2]
end
于 2013-01-07T21:18:06.047 に答える
0

必要な出力についていくつかの仮定を立て、編集します。

def transform(input)
  input.split.inject([]) do |ar, w|
    ar << (w == "case1" ? "add that" : "add these" + w) << "x"
  end[0..-2]
end

p transform("Hello case1 world!")

#=> ["add theseHello", "x", "add that", "x", "add theseworld!"]
于 2013-01-07T21:19:14.353 に答える