pdotsani
pdotsani

Reputation: 27

Capitalize Second Word in a String (ruby)

I'm trying to create a method to capitalize the second word in a string. The code below works, but I was wondering if there are other ways to do this:

def camelcase(string)
    tmp = string.split
    tmp[1].capitalize!
    tmp.join('')
end

Upvotes: 0

Views: 1224

Answers (4)

Agis
Agis

Reputation: 33626

Try this:

s = "foo bar"
s.sub(/\s(\w)/) { $1.capitalize } # => "fooBar"

Upvotes: 0

seph
seph

Reputation: 6076

You could use tap which "Yields x to the block, and then returns x" according to the docs. In this case capitalize! modifies x in place before being returned to the method chain for further processing by join.

def camelcase(string)
  string.split.tap { |words| words[1].capitalize! }.join
end

camelcase('foo bar baz')
=> "fooBarbaz"

Upvotes: 1

JordanD
JordanD

Reputation: 163

def camelcase(string)
    string.sub(/\s.*/) { |s|  s.delete(' ').capitalize}
end

puts camelcase("foo bar bas")
=> "fooBarbaz"

Upvotes: 1

spickermann
spickermann

Reputation: 106792

def camelcase(string)
  string.gsub(/\s(\w)/) { |match| $1.capitalize }
end

camelcase("foo bar baz") #=> "fooBarBaz"

Or you might wanna take a look at the camelcasemethod that comes with ActiveSupport::Inflector (see: http://apidock.com/rails/String/camelize)

Upvotes: 1

Related Questions