abcreddy
abcreddy

Reputation: 102

How to capitalise the last alphabet of each word present in the string in ruby?

How you capitalise the last alphabet of each word present in the string in ruby? For example:

Input String: the creator never dies Output String Must Be: thE creatoR neveR dieS

Note: Length of the string is not constant.

Upvotes: 0

Views: 116

Answers (3)

dimuch
dimuch

Reputation: 12818

your_string.gsub(/\w\b/) { |s| s.capitalize }

Upvotes: 5

Reuben Mallaby
Reuben Mallaby

Reputation: 5767

A quick and dirty way is:

(s.reverse.split(" ").each {|w| w.capitalize!}).join(" ").reverse
  • where s is your string

Upvotes: 1

Chowlett
Chowlett

Reputation: 46667

str.split.map do |word|
  word[-1] = word[-1].upcase
  word
end.join(' ')

That is - split the word at whitespace; form a new array of each word with the last character uppercased; join them back together

Upvotes: 1

Related Questions