字符串操纵

时间:2012-04-13 12:38:11

标签: ruby string

当然,除了从左到右,反之亦然,还有一种方法可以转换以下字符串

"content-management-systems" <=> "Content Management Systems"

这里有什么红宝石?

3 个答案:

答案 0 :(得分:5)

这很棘手:

puts "content-management-systems".split("-").map(&:capitalize).join(" ").
     tap{ |str| puts str}.
     split.map(&:downcase).join("-")

#=> Content Management Systems
#=> content-management-systems

简化版本:

"content-management-systems".split("-").map(&:capitalize).join(" ") 
#=> Content Management Systems

"Content Management Systems".split.map(&:downcase).join("-")
#=> content-management-systems

干净的变体(来自Micheal):

"content-management-systems".split("-").map(&:capitalize).join(" ").
split(" ").map(&:downcase).join("-")

答案 1 :(得分:2)

gsub regexp匹配可以在块模式下进行操作。

"content-management-systems".
  gsub(/(\w+)(-)?/) { ($2 ? $1 + " " : $1).capitalize! }.
  gsub(/(\w+)(\s)?/) { ($2 ? $1 + "-" : $1).downcase! }

并且正如这些基准测试显示正则表达式和 noregexp版本。

require 'benchmark'

STR = "content-management-systems".freeze

Benchmark.bmbm(10) do |x|
  x.report("noregexp") {
    STR.split("-").map(&:capitalize).join(" ").
    split(" ").map(&:downcase).join("-")
  }

  x.report("rgexp") {
    STR.
    gsub(/(\w+)(-)?/) { ($2 ? $1 + " " : $1).capitalize! }.
    gsub(/(\w+)(\s)?/) { ($2 ? $1 + "-" : $1).downcase! }
  }
end

__END__

Rehearsal ----------------------------------------------
noregexp     0.000000   0.000000   0.000000 (  0.000032)
rgexp        0.000000   0.000000   0.000000 (  0.000035)
------------------------------------- total: 0.000000sec

                 user     system      total        real
noregexp     0.000000   0.000000   0.000000 (  0.000051)
rgexp        0.000000   0.000000   0.000000 (  0.000058)

答案 2 :(得分:1)

我发布这个只是为了记住...... 正则表达式只是双倍的计算时间:

1.9.2p290 :014 > time = Benchmark.measure do
1.9.2p290 :015 >     puts "content-management-systems".split("-").map(&:capitalize).join(" ").
1.9.2p290 :016 >          tap{ |str| puts str}.
1.9.2p290 :017 >          split.map(&:downcase).join("-")
1.9.2p290 :018?>   end
Content Management Systems
content-management-systems
 =>   0.000000   0.000000   0.000000 (  0.000077)

1.9.2p290 :019 > time = Benchmark.measure do
1.9.2p290 :020 >     "content-management-systems".gsub(/(\w+)(-)?/) { ($2 ? $1 + " " : $1).capitalize! }
1.9.2p290 :021?>   "Content Management Systems".gsub(/(\w+)(\s)?/) { ($2 ? $1 + "-" : $1).downcase! }
1.9.2p290 :022?>   end
 =>   0.000000   0.000000   0.000000 (  0.000164)

我要感谢所有的贡献: - )