Ruby:使用反斜杠解析字符串

时间:2013-04-23 20:37:51

标签: ruby ruby-on-rails-3

string = "{:name=>\"2012 Honda Civic EX-L\", :price=>\"23100\", :dealer_name=>\"T AND T HOND\", :dealer_website=>\"http://autocatch.com/dealer/t-and-t-honda/index.htm\", :phone=>\"(888) 364-1858\", :ad=>\"1167269\", :stock=>\" 2120054N\", :year=>\"2012\", :make=>\"Honda\", :model=>\"Model Civic\", :trim=>\"EXL\", :mileage=>\"4629\", :body_style=>\"Coupe\", :transmission=>\"Automatic\", :ext_colour=>\"White\", :int_colour=>\"Grey\", :doors=>\"2Door\", :passengers=>\"Passengers \", :drive_train=>\"Front Wheel Drive\", :engine=>\"1.80\", :cylinders=>\"4Cylinder\", :fuel_type=>\"Type Gas\", :certified=>\"\", :e_tested=>\"\"}\n"

我该如何解析它? 它一直给我错误。

2 个答案:

答案 0 :(得分:1)

反斜杠正在逃避引号;它们实际上并不是 in 字符串。至于解析它,使用eval并让Ruby解析它,如果它来自可信来源。

答案 1 :(得分:1)

使用 ruby​​-2.0.0-p0

string = "{:name=>\"2012 Honda Civic EX-L\", :price=>\"23100\", :dealer_name=>\"T AND T HOND\", :dealer_website=>\"http://autocatch.com/dealer/t-and-t-honda/index.htm\", :phone=>\"(888) 364-1858\", :ad=>\"1167269\", :stock=>\" 2120054N\", :year=>\"2012\", :make=>\"Honda\", :model=>\"Model Civic\", :trim=>\"EXL\", :mileage=>\"4629\", :body_style=>\"Coupe\", :transmission=>\"Automatic\", :ext_colour=>\"White\", :int_colour=>\"Grey\", :doors=>\"2Door\", :passengers=>\"Passengers \", :drive_train=>\"Front Wheel Drive\", :engine=>\"1.80\", :cylinders=>\"4Cylinder\", :fuel_type=>\"Type Gas\", :certified=>\"\", :e_tested=>\"\"}\n"
hash = eval(string)
hash[:name] # => "2012 Honda Civic EX-L"

你到底有什么错误?