yaswant singh yaswant singh - 5 months ago 18
Ruby Question

regular expression a string

I Need a regular expression which will convert the following object:

"{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}"


to

Email has already been taken, Name has already been taken

Answer
▶ str = "{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}"
▶ eval(str).map { |k, v| [k.capitalize, v].join(' ') }.join(', ')
#⇒ "Email has already been taken, Name has already been taken"

With scan:

▶ str.scan(/:(\w+)=>\["(.*?)"\]/).map do |k, v|
▷   [k.capitalize, v].join(' ')
▷ end.join(', ')
#⇒ "Email has already been taken, Name has already been taken"