I only want to capitalize the first char and leave the others as is.
For example:
"fooBar".titleize
returns "Foo Bar"
. Should return FooBar.
"foo_Bar".capitalize
returns "Foo_bar"
Should return Foo_Bar.
Any way I can do th开发者_如何学运维is?
irb(main):001:0> s = "foo_Bar"
=> "foo_Bar"
irb(main):002:0> s[0] = s[0].upcase
=> "F"
irb(main):003:0> s
=> "Foo_Bar"
Or with regex for in-place substitution:
irb(main):001:0> s = "foo_Bar"
=> "foo_Bar"
irb(main):002:0> s.sub!(/^\w/) {|x| x.upcase}
=> "Foo_Bar"
class String
def fazzinize
first, *last = self.split("_")
[first.capitalize, *last].join("_")
end
end
"fooBar".fazzinize
#=> "Foobar"
"foo_Bar".fazzinize
#=> "Foo_Bar"
UPD
if it is a typo:
"fooBar".titleize returns "Foo Bar". Should return Foobar -> FooBar
then @Mchi is right
class String
def fazzinize
self[0] = self[0].upcase; self;
end
end
irb(main):001:0> s = "foo_Bar"
=> "foo_Bar"
irb(main):002:0> s1 = s.slice(0,1).capitalize + s.slice(1..-1)
=> "Foo_Bar"
Just substitute the first character with its uppercase version using a block.
"fooBar".sub(/^./) { |char| char.upcase }
精彩评论