简体   繁体   English

在 Ruby 字符串中查找哈希值

[英]Find hashes in a Ruby string

I have a string that looks like this:我有一个看起来像这样的字符串:

greetings = <<-GREETINGS
[{a: "hello", b: "goodbye"}, {a: "guten tag", b: "auf wiedersehen"}]
GREETINGS

How can I split this string, so as to return an Array of the Hashes?我怎样才能拆分这个字符串,以便返回一个哈希数组?

require 'json'

JSON.parse(greetings.gsub(/(\p{Alnum})+:/, '"\1":')).
     map { |h| h.transform_keys(&:to_sym) }
  #=> [{:a=>"hello", :b=>"goodbye"},
  #    {:a=>"guten tag", :b=>"auf wiedersehen"}] 

The steps are as follows:步骤如下:

str = greetings.gsub(/(\p{Alnum})+:/, '"\1":')
  #=> "[{\"a\": \"hello\", \"b\": \"goodbye\"}, {\"a\": \"guten tag\", \"b\": \"auf wiedersehen\"}]\n"

arr = JSON.parse(str)
  #=> [{"a"=>"hello", "b"=>"goodbye"},
  #    {"a"=>"guten tag", "b"=>"auf wiedersehen"}] 
arr.map { |h| h.transform_keys(&:to_sym) } 
  #=> [{:a=>"hello", :b=>"goodbye"},
  #    {:a=>"guten tag", :b=>"auf wiedersehen"}] 

The regular expression reads, "match one or more alphanumeric characters in capture group 1 followed by a colon".正则表达式显示为“匹配捕获组 1 中的一个或多个字母数字字符,后跟一个冒号”。 The \\1 in gsub 's replacement string is replaced with the contents of capture group 1. gsub的替换字符串中的\\1被替换为捕获组 1 的内容。

See JSON::parse , String#gsub and Hash#transform_keys .请参阅JSON::parseString#gsubHash#transform_keys

If you trust the source (and only if you trust the source, which is probably not true):如果您信任来源(并且当您信任来源时,这可能不是真的):

data = eval(str)

If you do not (which should be close to 100% of cases), then you can use the parsr gem如果您不这样做(应该接近 100% 的情况),那么您可以使用parsr gem

data = Parsr.literal_eval(str)

You could also write your own grammar, but... why?您也可以编写自己的语法,但是...为什么? :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM