Ruby capitalize在map方法中不起作用
我正在尝试将字符串的第一个字母转换为大写字符。我正试图转向:Ruby capitalize在map方法中不起作用,ruby,string,Ruby,String,我正在尝试将字符串的第一个字母转换为大写字符。我正试图转向: "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"
进入:
这是我的密码:
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
item.capitalize
在map
循环中起作用,如果我把pry的binding.pry放在那里
我没有正确使用map
方法吗?map方法不会改变它的接收者,而是返回一个新的修改副本。您可以使用它的突变/破坏对应map
或只是将表达式的值重新分配给变量
arr_str.map! do |item|
item.capitalize
end
# ... or ...
arr_str = arr_str.map do |item|
item.capitalize
end
它“不起作用”正如你所期望的那样。因为capitalize将capitalize方法应用于项目,接收者,然后返回您的arr_str
的新表示,从而生成块内的内容。换句话说,正如文件所述:
映射{obj | block}→ 数组单击以切换源
地图→ 枚举器
返回一个新数组,其中包含每次运行一次块的结果
枚举中的元素
如果您使用“持久化”方法来修改您的arr\u str
,就像地图的兄弟一样,它的工作原理略有不同:
地图!{|项|块}→ 单击以切换源
地图!→ 枚举器
为self的每个元素调用一次给定的块,用块返回的值替换元素
您的代码现在正在做的是拆分传递的字符串,在生成和存储的拆分结果中迭代每个元素,并对这些元素应用capitalize,最后连接它们并使用put打印它们:
def first_upper(str)
arr_str = str.split # ["this", "is", "a", "test", "sentence"]
arr_str.map do |item|
item.capitalize
end # ["This", "Is", "A", "Test", "Sentence"]
arr_str = arr_str.join(' ') # this is a test sentence
puts arr_str # this is a test sentence
end
first_upper('this is a test sentence')
最简单和最明显的方法是:
A) 将arr_str.map
的结果存储在该步骤后要在函数中使用的变量中。
B) 使用地图!通过这种方式修改arr_str并“持续”在该块中执行的操作。只需添加我的两分钱
以下是一些方法,将monkey补丁到String
类中
module MyStringPatch
def titleize_1
split(' ').collect(&:capitalize).join(' ') # Stolen from user3869936
end
def titleize_2
gsub(/\b(?<!['â`])[a-z]/) { |match| match.capitalize } # Stolen from Rails
end
def titleize_3
split.map { |item| item.capitalize }.join(' ') # Stolen from OP: user4396386
end
end
String.include MyStringPatch
string = "this is a test sentence"
p string.titleize_1 # => "This Is A Test Sentence"
p string.titleize_2 # => "This Is A Test Sentence"
p string.titleize_3 # => "This Is A Test Sentence"
模块MyStringPatch
def titleize_1
拆分(“”)。收集(&:大写)。加入(“”)#从用户3869936处窃取
结束
def titleize_2
gsub(/\b(?Try withmap!
Ahh),因此我用map创建了一个数组,但没有将它分配给任何对象。map!替换原始数组的元素。谢谢!您的意思是:“将字符串的第一个字母转换为大写字符”还有第三种选择:使用item.capitalize!
(不过,如果您不确定在哪里重复使用东西,那么非破坏性的arr\u str=…
方法是最安全的。)
module MyStringPatch
def titleize_1
split(' ').collect(&:capitalize).join(' ') # Stolen from user3869936
end
def titleize_2
gsub(/\b(?<!['â`])[a-z]/) { |match| match.capitalize } # Stolen from Rails
end
def titleize_3
split.map { |item| item.capitalize }.join(' ') # Stolen from OP: user4396386
end
end
String.include MyStringPatch
string = "this is a test sentence"
p string.titleize_1 # => "This Is A Test Sentence"
p string.titleize_2 # => "This Is A Test Sentence"
p string.titleize_3 # => "This Is A Test Sentence"