O
O
Ord EO2020-01-09 15:38:39
ruby
Ord EO, 2020-01-09 15:38:39

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

The problem is that the '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 .capitalizeit, 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

3 answer(s)
S
Sergey Blokhin, 2020-01-09
@TITnet

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

Below is an `RSpec` test for the method, just in case.
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

D
Dmitry Shitskov, 2020-01-09
@Zarom

words = "some String" 
words[0] = words[0].capitalize

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question