简体   繁体   English

从 String / Ruby 中提取 Substring

[英]Extract Substring from String / Ruby

I get the datas from a variable called "apps".我从一个名为“apps”的变量中获取数据。

And I have this datastructure:我有这个数据结构:

{"id"=>001,
 "name"=>"test01",
 "users"=>
 [{"id"=>01,
   "name"=>"test02"},
  {"id"=>02,
   "name"=>"test03"}]}

How can I extract the namevalues from the users substring?如何从用户 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 中提取名称值?

I have tried我努力了

apps.each do |test|
  data = Hash.new
  data['id'] = test['id']
  data['name'] = test['name']
  data['username'] = test['users.name']
  userdata = data
  userdata.each do |row|
    File.write('test.yaml', row.to_yaml)
  end
end

But that doesn't work.但这不起作用。

desired output would be:所需的 output 将是:

{"id"=>"01", "name"=>"test02","id"=>"02", "name"=>"test03"} {"id"=>"01", "name"=>"test02","id"=>"02", "name"=>"test03"}

you just need to require 'yaml' in order to use it on Hash/Array classes, you don't need to iterate over array or hash, to_yaml already handles this for you.您只需要require 'yaml'就可以在 Hash/Array 类上使用它,您不需要遍历数组或 hash, to_yaml已经为您处理了这个问题。

require 'yaml'

data = {"id"=>001,
 "name"=>"test01",
 "users"=>
 [{"id"=>01,
   "name"=>"test02"},
  {"id"=>02,
   "name"=>"test03"}]}

File.write('test.yml', data["users"].to_yaml)

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

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