0

我想大写一个数组,但得到了这种行为:

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

为了这:

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

为什么单词不是大写的?

(在我解决这个问题时,现在忽略实际的订单)。

4

3 回答 3

1

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)
于 2012-07-09T23:26:04.110 回答
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收集到一个新数组中。

于 2012-07-09T23:33:05.877 回答
0

您没有改变输入数组。尽管每个在迭代时实际上都是大写的,但原始数组将被原封不动地返回。改用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"]
于 2012-07-09T23:24:15.383 回答