什么不是e.upcase返回大写单词

时间:2012-07-09 23:21:45

标签: ruby arrays

我想大写一个数组但是有这种行为:

=> ["this", "set", "of", "words", "is", "in", "a", "certain", "order"] 

为此:

%w[this set of words is in a certain order].each {|e| e.upcase}

为什么单词不是大写的?

(当我解决这个问题时,忽略实际的排序现在可以解决这些问题了。)

3 个答案:

答案 0 :(得分:1)

String#upcase返回一个新的字符串值,它不会修改接收者。使用String#upcase!获取所需的行为,或使用map生成一个新的upcased值数组。

%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)

答案 1 :(得分:1)

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为您收集新数组中的所有结果。

答案 2 :(得分:0)

您没有改变输入数组。尽管在迭代时每个实际上都是upcased,但原始数组将保持不变。请改用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"]