如何将其转换为,然后从此数组中提取特定的东西?

时间:2011-09-08 14:21:52

标签: ruby arrays irb

我将Facebook喜欢保存在表格中(它们在字符串中)并在控制台中执行以下操作以使用类似方法为用户模型返回喜欢的内容:

  
    

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"

下面是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

我希望最终结果给我一些类似的东西:

>> ["Rome sweet Rome", "Drawn Together"]

1 个答案:

答案 0 :(得分:2)

将字符串拆分为单独的行,由\n字符分隔(或者如果它作为字符串“\ n”出现,请使用双引号分隔该字符串)

like_elements = User.first.likes.split("\n") # <- String, not character, delimited version
=> ['id: "136333439795671"', 'created_time: 2011-09-05T12:03:09+0000", "- name: Drawn Together" ... etc.]

然后将所有以“ - name:”开头的元素收集到它们自己的数组中:

name_elements = like_elements.select{|s| s.start_with?("- name: ")}
=> ["- name: Drawn Together", "- name: Rome sweet Rome"]

然后获取name_elements中的每个元素并删除前导"- name: "文本,并删除前导空格

names_of_likes_only = name_elements.collect{|n| n.gsub("- name: ", "").strip}
=> ["Drawn Together", "Rome sweet Rome"]