我需要一个正则表达式,它将转换以下对象:
"{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}"
到
Email has already been taken, Name has already been taken
答案 0 :(得分:2)
▶ 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"
使用scan
:
▶ str.scan(/:(\w+)=>\["(.*?)"\]/).map do |k, v|
▷ [k.capitalize, v].join(' ')
▷ end.join(', ')
#⇒ "Email has already been taken, Name has already been taken"
答案 1 :(得分:0)
另一种方法:
def convert(str)
arr = [' '].concat str.chars
str.gsub(/./) do |c|
case arr.shift
when ':' then c.upcase
when '=' then ' '
else c =~ /[,\sa-zA-Z]/ ? c : ''
end
end
end
str = '{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}'
convert str
#=> "Email has already been taken, Name has already been taken"