正则表达式字符串

时间:2015-10-27 16:17:35

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems

我需要一个正则表达式,它将转换以下对象:

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

Email has already been taken, Name has already been taken

2 个答案:

答案 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"