【问题标题】:Ruby capitalize is not working inside the map methodRuby capitalize 在 map 方法中不起作用
【发布时间】:2018-08-30 02:09:19
【问题描述】:

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

"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!
  • 啊,所以我用地图创建了一个数组,但没有将它分配给任何东西。地图!替换原始数组的元素。谢谢!
  • 你说的是:“把字符串的第一个字母变成大写字符”,你所期待的不一样。

标签: ruby string


【解决方案1】:

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

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

# ... or ...

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

【讨论】:

  • 还有第三种选择:使用item.capitalize! 改变字符串本身。 (虽然,如果你不确定东西在哪里被重复使用,非破坏性的arr_str = ... 方式是最安全的。)
【解决方案2】:

它“不起作用”,正如您所期望的那样。当 capitalize 对 item 应用 capitalize 方法时,接收器,然后返回你的 arr_str 的新表示,产生块内的内容。换句话说,正如文档所述:

地图 { |obj|块 } → 数组单击以切换源
地图 → an_enumerator
每次返回一个新数组,其中包含一次运行块的结果 枚举中的元素。

如果您使用“持久”方法来修改您的arr_str,就像地图的兄弟Array#map!,其工作方式略有不同:

地图! {|项目|块 } → ary 点击切换源
地图! → 枚举器
为 self 的每个元素调用一次给定块,将元素替换为块返回的值。

您的代码现在正在做的是拆分传递的字符串,迭代生成和存储的拆分结果中的每个元素,并在这些元素上应用资本化,最后加入它们并使用 puts 打印它们:

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 并“保留”该块中正在执行的操作。

【讨论】:

    【解决方案3】:

    只是为了加我的两分钱..

    这些是一些方法,猴子修补到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"
    

    学分:

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 2021-11-15
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多