我有一个像这样的字符串:
price<=>656000<br>bathrooms<=>1<br>bedrooms<=>3<br>pets<=>1<br>surface<=>60<br>brokerfree<=>1 model<=>opel/corsa<br>mileage<=>67000<br>vinnumber<=>unknown<br>price<=>145000<br>year<=>2010<br>condition<=>2<br>transmission<=>unknown<br>cartype<=>1
我想要哈希:
:model => 'opel/corsa'
等等......字符串是可变的,所以这也是有效的:
year<=>2015<br>condition<=>1<br>price<=>2100mileage<=>22000<br>price<=>120000<br>year<=>2012<br>condition<=>2
或者
price<=>656000<br>bathrooms<=>1<br>bedrooms<=>3<br>pets<=>1<br>surface<=>60<br>brokerfree<=>1
model<=>opel/corsa<br>mileage<=>67000<br>vinnumber<=>unknown<br>price<=>145000<br>year<=>2010<br>condition<=>2<br>transmission<=>unknown<br>cartype<=>1
答案 0 :(得分:4)
您不需要正则表达式。您可以使用普通红宝石方法。
v3
答案 1 :(得分:0)
您也可以使用Array的.to_h方法,请参阅以下示例。
string = "model<=>opel/corsa<br>mileage<=>67000<br>vinnumber<=>unknown<br>price<=>145000<br>year<=>2010<br>condition<=>2<br>transmission<=>unknown<br>cartype<=>1"
hash = string.split('<br>').map{|a| a.split('<=>')}.to_h
## OUTPUT
{"model"=>"opel/corsa", "mileage"=>"67000", "vinnumber"=>"unknown", "price"=>"145000", "year"=>"2010", "condition"=>"2", "transmission"=>"unknown", "cartype"=>"1"}
答案 2 :(得分:0)
如果str
是您的字符串,您可以按如下方式构建哈希:
Hash[*str.split(/<=>|<br>/)]
#=> {"price"=>"145000", "bathrooms"=>"1", "bedrooms"=>"3", "pets"=>"1",
# "surface"=>"60", "brokerfree"=>"1", "model"=>"opel/corsa",
# "mileage"=>"67000", "vinnumber"=>"unknown", "year"=>"2010",
# "condition"=>"2", "transmission"=>"unknown", "cartype"=>"1"}
第二个例子:
str = "year<=>2015<br>condition<=>1<br>price<=>2100<br>mileage<=>22000"+
"<br>price<=>120000<br>year<=>2012<br>condition<=>2"
Hash[*str.split(/<=>|<br>/)]
#=> {"year"=>"2012", "condition"=>"2", "price"=>"120000", "mileage"=>"22000"}