有时我喜欢学习如何以“Ruby”的方式做事。我想知道 - 采用如下字符串的最简洁,最可读的方式是什么:
foo-bar
并操纵它阅读:
Foo Bar
答案 0 :(得分:5)
"foo-bar".split("-").map(&:capitalize).join(" ")
答案 1 :(得分:1)
"foo-bar".gsub(/\b(\w)/){|m| m.capitalize}.sub '-', ' '
答案 2 :(得分:0)
>> p "foo-bar".scan(/\w+/).map(&:capitalize).join(" ")
"Foo Bar"
=> "Foo Bar"
>> p "foo---bar".scan(/\w+/).map(&:capitalize).join(" ")
"Foo Bar"
=> "Foo Bar"
>> p "foo 123 bar".scan(/\w+/).map(&:capitalize).join(" ")
"Foo 123 Bar"
=> "Foo 123 Bar"
答案 3 :(得分:0)
string = "foo-bar"
"foo-bar".split("-").map(&:capitalize).join(" ") # edited to because former answer was not optimal