仅遍历以大写字母为目标的数组

问题描述 投票:0回答:2

我试图遍历一个我已转换为数组的字符串,并且只定位大写字母,然后我将在大写字母之前插入一个空格。我的代码检查第一个大写字母并添加空格,但是正努力为下一个大写字母(在这种情况下为“ T”)执行此操作。任何建议将不胜感激。谢谢

  def break_camel(str)
  # ([A-Z])/.match(str)
  saved_string = str.freeze
  cap_index =str.index(/[A-Z]/)
  puts(cap_index)

   x =str.split('').insert(cap_index, " ")
  x.join

end
break_camel("camelCasingTest")
ruby-on-rails ruby ruby-on-rails-3
2个回答
0
投票

您必须实现自己的吗?似乎标题为https://apidock.com/rails/ActiveSupport/Inflector/titleize的内容已涵盖。


0
投票

我认为您的方法正在寻求继续重新应用您的方法,直到需要为止。您代码的一种扩展是使用递归:

def break_camel(str)
  regex = /[a-z][A-Z]/
  if str.match(regex)
    cap_index = str.index(regex)
    str.insert(cap_index + 1, " ")
    break_camel(str)
  else
    str  
  end
end

break_camel("camelCasingTesting") #=> "camel Casing Testing"

注意方法内部的break_camel方法。另一种方法是通过使用scan方法在重新加入它们之前传递适当的正则表达式。

使用代码:

scan
© www.soinside.com 2019 - 2024. All rights reserved.