Christian Fazzini
Christian Fazzini

Reputation: 19723

Capitalize first char and leave others as is

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 this?

Upvotes: 4

Views: 165

Answers (4)

edgerunner
edgerunner

Reputation: 14973

Just substitute the first character with its uppercase version using a block.

"fooBar".sub(/^./) { |char| char.upcase }

Upvotes: 0

fl00r
fl00r

Reputation: 83680

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

Upvotes: 4

Dnyan Waychal
Dnyan Waychal

Reputation: 1418

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"

Upvotes: 1

Mchl
Mchl

Reputation: 62377

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"

Upvotes: 4

Related Questions