我如何将其转换为,然后从该数组中提取特定的内容?
我将 Facebook 点赞保存在表中(它们位于字符串中),并在控制台中执行以下操作,以使用用户模型的 like 方法返回点赞:
<块引用>用户.first.likes
=> "--- !seq:Koala::Facebook::GraphCollection \n- name: Rome Sweet Rome\n category:
Book\n id: \"136333439795671\"\n created_time: 2011-09-05T12:03:09+0000\n- name:
Drawn Together\n category: Tv show\n id: \"8694990902\"\n created_time:
2008-10-03T10:39:46+0000\n"
下面是 YAML 中的内容:
<块引用>y 用户.first.likes
--- |
--- !seq:Koala::Facebook::GraphCollection
- name: Rome Sweet Rome
category: Book
id: "136333439795671"
created_time: 2011-09-05T12:03:09+0000
- name: Drawn Together
category: Tv show
id: "8694990902"
created_time: 2008-10-03T10:39:46+0000
=> nil
我希望最终结果给我类似的东西:
>> ["Rome sweet Rome", "Drawn Together"]
I have Facebook likes saved in a table (they're in a string) and do the following in the console to return the likes using the like method for the user model:
User.first.likes
=> "--- !seq:Koala::Facebook::GraphCollection \n- name: Rome Sweet Rome\n category:
Book\n id: \"136333439795671\"\n created_time: 2011-09-05T12:03:09+0000\n- name:
Drawn Together\n category: Tv show\n id: \"8694990902\"\n created_time:
2008-10-03T10:39:46+0000\n"
Below it is in YAML:
y User.first.likes
--- |
--- !seq:Koala::Facebook::GraphCollection
- name: Rome Sweet Rome
category: Book
id: "136333439795671"
created_time: 2011-09-05T12:03:09+0000
- name: Drawn Together
category: Tv show
id: "8694990902"
created_time: 2008-10-03T10:39:46+0000
=> nil
I want the end result to give me something like:
>> ["Rome sweet Rome", "Drawn Together"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将字符串拆分为单独的行,由
\n
字符分隔(或者如果它出现为字符串“\n”,则使用双引号对该字符串进行分隔)然后收集所有以将“- name:”放入自己的数组中:
然后取出
name_elements
中的每个元素,并去掉前导的"- name: "
文本,并删除前导和尾随的文本空白Split the string into separate lines, delimited by the
\n
character (or if it comes across as the string "\n", use double-quotes to delimit on that string)Then collect all elements that start with "- name: " into their own array:
Then take each of the elements in
name_elements
and strip out the leading"- name: "
text, and remove leading an trailing whitespace