配列を大文字にしたかったのですが、この動作になりました:
=> ["this", "set", "of", "words", "is", "in", "a", "certain", "order"]
このため:
%w[this set of words is in a certain order].each {|e| e.upcase}
単語が大文字にならなかったのはなぜですか?
(この問題を解決している間、実際の注文は無視してください)。
irb> %w[this set of words is in a certain order].map {|e| e.upcase}
=> ["THIS", "SET", "OF", "WORDS", "IS", "IN", "A", "CERTAIN", "ORDER"]
each
すべての結果をmap
破棄し、すべての結果を新しい配列に収集します。
String#upcase
新しい文字列値を返します。レシーバーは変更されません。を使用String#upcase!
して必要な動作を取得するか、map を使用して大文字の値の新しい配列を生成します。
%w[this set of words is in a certain order].each { |e| e.upcase! }
up_words = %w[this set of words is in a certain order].map(&:upcase)
入力配列を変更していません。反復中にそれぞれが実際には大文字になりますが、元の配列は変更されずに返されます。upcase!
代わりに使用してください:
# Modifies the array in place and returns the modified version:
>> %w[this set of words is in a certain order].each {|e| e.upcase!}
=> ["THIS", "SET", "OF", "WORDS", "IS", "IN", "A", "CERTAIN", "ORDER"]
# Assign it to a variable to get the up-cased array:
up_cased = %w[this set of words is in a certain order].each {|e| e.upcase!}
up_cased
# => ["THIS", "SET", "OF", "WORDS", "IS", "IN", "A", "CERTAIN", "ORDER"]
それらを に出力するeach
と、大文字と小文字が区別されますが、変更されていない元の配列が返されます。
# Calls upcase for proof, but the original array is still returned:
>> %w[this set of words is in a certain order].each {|e| puts e.upcase}
THIS
SET
OF
WORDS
IS
IN
A
CERTAIN
ORDER
=> ["this", "set", "of", "words", "is", "in", "a", "certain", "order"]
変数を操作すると、少し見やすくなります。
arr = %w[this set of words is in a certain order]
# upcase, but don't modify original
arr.each {|e| e.upcase}
arr.inspect
# ["this", "set", "of", "words", "is", "in", "a", "certain", "order"]
# now modify in place with upcase!
arr.each {|e| e.upcase!}
arr.inspect
# ["THIS", "SET", "OF", "WORDS", "IS", "IN", "A", "CERTAIN", "ORDER"]