Answer the question
In order to leave comments, you need to log in
How to capitalize the first letter using regular expressions in ruby?
there is a function that processes a certain array of hashes:
def get_document(document)
document.map do |doc|
{
'Type' => doc['doc_type'],
'Name' => doc['name'],
'No.' => doc['doc_number'],
'Address' => doc['address'],
'Date' => doc['doc_exp']
}
end
end
'Type' => doc['doc_type']
data comes in the form of a sentence of 5-6 words where the first word is always with a small letter, and the rest with a capital letter, I need the first word to also be capitalized. When I use .capitalize
it, only the first word becomes capitalized, and the rest become small, how can I do this correctly, there is an assumption that, perhaps, through regular expressions, but I don’t know them.
Answer the question
In order to leave comments, you need to log in
I had a similar task.
It was necessary to convert the “first name patronymic surname” into “first name patronymic surname”.
Decided through the extension of the standard class `class String`.
The `#capitalize_words` method splits the string into an array of words and iterates over each word and "capitalizes" it.
After that, it collects the array into the original string.
class String
# @see String#capitalize
def capitalize_words(separator = ' ')
words = split(separator).map(&:capitalize)
words.join separator
end
end
describe String do
describe '#capitalize_words' do
context 'with word' do
let :one_word do
'foo'
end
it 'return capitalized word' do
expect(one_word.capitalize_words).to eq 'Foo'
end
end
context 'with words' do
let :words do
'foo bar'
end
it 'return capitalized all words' do
expect(words.capitalize_words).to eq 'Foo Bar'
end
end
context 'with custom separator' do
let :words do
'foo$bar'
end
let :custom_separator do
'$'
end
it 'return capitalized with custom separator' do
expect(words.capitalize_words(custom_separator)).to eq 'Foo$Bar'
end
end
context 'with empty' do
let :empty do
''
end
it 'return empty' do
expect(empty.capitalize_words).to eq empty
end
end
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question