如何在ruby中解析字符串?

时间:2014-10-15 16:19:54

标签: ruby-on-rails ruby string parsing

在db-table中我有这样的字符串:

#<ActiveRecord::RecordInvalid: Validation failed: Profile is not valid: Given name: can't be blank; Family name: can't be blank>"

我只需提取错误消息:

Validation failed: Profile is not valid: Given name: can't be blank; Family name: can't be blank

记录总是从#开始

谁能帮帮我?

3 个答案:

答案 0 :(得分:0)

您无需解析它,您只需要更具体地询问:

file.import_entries.last.last_exception.to_s

您所看到的是inspect的结果,pryirb

等工具默认调用此方法

按惯例,#表示数据的开头。一个类可以自由地实现他们想要的任何inspect方法,并且许多产生相当不规则的结果。

<强>更新

如果您已经完全抓住了这一点并需要恢复原件,那么您可以这样做:

file.import_entries.last.last_exception.scan(/#<([^>]+)>/).flatten.join

答案 1 :(得分:0)

假设由于某种原因您将结果保存为数据库中的字符串:

file.import_entries.last.last_exception.match(/Validation(.*)$/)

答案 2 :(得分:0)

这会将错误提取到errors Hash中,类似于原始对象中错误的表示方式:

s = "Validation failed: Profile is not valid: Given name: can't be blank; Family name: can't be blank"
errors = {}

error_strings = s.split('not valid:').last.split(';')
error_strings.each do |error_string|
  label, message = error_string.split(':')
  attribute_name = label.strip.parameterize.underscore
  errors[attribute_name] = message.strip
end

puts errors
# => {"given_name" => "can't be blank", "family_name" => "can't be blank"}