O
O
Ord EO2019-07-12 03:24:05
ruby
Ord EO, 2019-07-12 03:24:05

How to replace comma with brackets in ruby?

There is such a line "Hello everybody, my name is alex"
How to make it so that the text after the comma was wrapped in brackets and each word in brackets began with a capital letter?
This is the result:
Hello everybody (My Name Is Alex)
Something like this, but instead of an array, it would take a string

def change_comma(word)
  word.map do |el|
    if el =~ /.+,.+/
      e = el.split(',')
      e[0] + ' (' + (e[1].split.map(&:capitalize).join(' ')) + ')'
    else
      el
    end
  end
end

Now, in order to make it work, you need to wrap it in an array, like this:change_comma(["Hello everybody, my name is alex"])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Alekseiev, 2019-07-12
@OrdeO

def change_comma(sentence)
 return sentence if !sentence.is_a?(::String) || !sentence.include?(',')
 first_part, second_part = sentence.split(',', 2)[0], sentence.split(',', 2)[1]
 "#{first_part} (#{second_part.split.map(&:capitalize).join(' ')})"
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question