How to capitalize the first letter in a String in Ruby
It depends on which Ruby version you use:
Ruby 2.4 and higher:
It just works, as since Ruby v2.4.0 supports Unicode case mapping:
"мария".capitalize #=> Мария
Ruby 2.3 and lower:
"maria".capitalize #=> "Maria"
"мария".capitalize #=> мария
The problem is, it just doesn't do what you want it to, it outputs мария
instead of Мария
.
If you're using Rails there's an easy workaround:
"мария".mb_chars.capitalize.to_s # requires ActiveSupport::Multibyte
Otherwise, you'll have to install the unicode gem and use it like this:
require 'unicode'
Unicode::capitalize("мария") #=> Мария
Ruby 1.8:
Be sure to use the coding magic comment:
#!/usr/bin/env ruby
puts "мария".capitalize
gives invalid multibyte char (US-ASCII)
, while:
#!/usr/bin/env ruby
#coding: utf-8
puts "мария".capitalize
works without errors, but also see the "Ruby 2.3 and lower" section for real capitalization.
Ruby capitalize every word first letter
try this:
puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')
#=> One Two Three Four
or
puts 'one TWO three foUR'.split.map(&:capitalize)*' '
How to convert a string to lower or upper case in Ruby
Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase
:
"hello James!".downcase #=> "hello james!"
Similarly, upcase
capitalizes every letter and capitalize
capitalizes the first letter of the string but lowercases the rest:
"hello James!".upcase #=> "HELLO JAMES!"
"hello James!".capitalize #=> "Hello james!"
"hello James!".titleize #=> "Hello James!" (Rails/ActiveSupport only)
If you want to modify a string in place, you can add an exclamation point to any of those methods:
string = "hello James!"
string.downcase!
string #=> "hello james!"
Refer to the documentation for String for more information.
Capitalize each word in an array
The documentation for String#capitalise
says:
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
That's not what you're trying to do. So you need to write something custom instead.
For example:
array.map { |string| string.gsub(/\b[a-z]/, &:upcase) }
I'm not clear if/how you plan to handle other input such as all-caps, or hyphenated words, or multiple lines, ... But if your requirements get more detailed then you may need to expand on this implementation.
Capitalize only first character of string and leave others alone? (Rails)
Titleize will capitalise every word.
This line feels hefty, but will guarantee that the only letter changed is the first one.
new_string = string.slice(0,1).capitalize + string.slice(1..-1)
Update:
irb(main):001:0> string = "i'm from New York..."
=> "i'm from New York..."
irb(main):002:0> new_string = string.slice(0,1).capitalize + string.slice(1..-1)
=> "I'm from New York..."
Capitalize the first letter of each word - Ruby
Do as below using Array#map
:
text.split.map { |i| i.capitalize }.join(' ')
Corrected and short code :
text= "a bunny hops"
final = text.split.map(&:capitalize).join(' ')
puts final
# >> A Bunny Hops
Why didn't your one worked :
Because Array#each
method returns the receiver itself on which it has been called :
text= "a bunny hops"
text.split.each(&:capitalize) # => ["a", "bunny", "hops"]
But Array#map
returns a new array
text.split.map(&:capitalize) # => ["A", "Bunny", "Hops"]
I would do it as below using String#gsub
:
text= "a bunny hops"
text.gsub(/[A-Za-z']+/,&:capitalize) # => "A Bunny Hops"
Note: The pattern I used here with #gsub
, is not the trivial one. I did it as per the string have been given in the post itself. You need to change it as per the text string samples you will be having. But the above is a way to do such things with short code and more Rubyish way.
How to make only the first element of a array capitalize in Ruby
Since version 1.9.3, Ruby has had Enumerator#with_index. The method map
without a block returns an Enumerator
, so you can do the following:
final_title = words.map.with_index do |word, i|
if i != 0 && (word == "and" || word == "the" || word.length < 3)
word.downcase
else
word.capitalize
end
end
Clearly, you should make sure your title is lowercase to begin with, or the code checking for "and" and "the" won't work.
Related Topics
How to Get the Current Time as 13-Digit Integer in Ruby
How Does Shovel (<<) Operator Work in Ruby Hashes
Why Does My Ruby 'Ri' Tool Not Return Results in Command Prompt
What Does 'Def Self.Function' Name Mean
How to Configure Capistrano to Use My Rvm Version of Ruby
Rails 3. How to Display Two Decimal Places in Edit Form
Activerecord - Querying Polymorphic Associations
Differencebetween 'After_Create' and 'After_Save' and When to Use Which
Gem.Source_Index Is Deprecated, Use Specification. Should I Re-Install Gem or Rails
Get the Value of an Instance Variable Given Its Name
How to Make Instance Variables Private in Ruby
How to Print Out the Contents of an Object in Rails for Easy Debugging
Using Instance Variables in Class Methods - Ruby
How to Change All the Keys of a Hash by a New Set of Given Keys
Rvm Ruby 1.9.1 Install Can't Locate Zlib But Its Runtime and Dev Library Are There