gpt4 book ai didi

Ruby capitalize 在 map 方法中不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:47 25 4
gpt4 key购买 nike

我正在尝试将字符串的首字母转换为大写字符。我正在尝试转向:

"this is a test sentence"

进入:

"This Is A Test Sentence"

这是我的代码:

def first_upper(str)
arr_str = str.split
arr_str.map do |item|
item.capitalize
end
arr_str = arr_str.join(' ')
puts arr_str
end

first_upper('this is a test sentence')
# >> this is a test sentence
如果我将 pry 的 binding.pry 放在那里,

item.capitalizemap 循环中工作。

我没有正确使用 map 方法吗?

最佳答案

'map' 方法不会改变它的接收者,而是返回一个新的修改后的副本。您可以使用它的可变/破坏性对应物 map! 或只是将表达式的值重新分配给变量。

arr_str.map! do |item|
item.capitalize
end

# ... or ...

arr_str = arr_str.map do |item|
item.capitalize
end

关于Ruby capitalize 在 map 方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52088306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com