2

Sure enough there are more than a way to convert the following strings either form left to right or vice versa

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

What's the ruby way here ?

4

3 回答 3

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("-")
于 2012-04-13T12:52:15.353 回答
2

gsub正则表达式匹配可以在块模式下进行操作。

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

由于这些基准测试显示 regexp 和 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)
于 2012-04-13T13:20:45.857 回答
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)

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

于 2012-04-13T13:27:23.590 回答