-1

我正在尝试将数组放入哈希中:

@friends = {}
@friend = ['network' => 'facebook', 'picture' => picture, 'name' => name, 'id' => id]

我怎样才能@friend进入@friends以获得以下结果:

friends: {
  [
    'network': 'facebook',
    'picture': 'http://fb.com/myimage.jpg',
    'name':    'MyName',
    'id':      '46846546'
  ]
}

我能做到的arrayarray一个hasharray我也能做到。但是array在一个hash- 我找不到怎么做。

这可能是不可能的。我正在搜索哈希和数组的文档,但对此一无所知。

对于与最后评论相关的@dave newton:

在此处输入图像描述

对于与他的回答相关的@Borodin:

在此处输入图像描述

4

2 回答 2

1

您不能“将数组放入散列”以获得类似{[]}. 哈希是从键值对构建的。数组可以在散列中担任键或值角色。

例如,这里数组是值,符号:friends是键:

{:friends => ['Pete', 'Robert', 'Katrin']}

@friend变量(如您所定义的那样)产生一个具有一个元素的数组,该元素是一个散列。

@friend = ['network' => 'facebook', 'picture' => picture, 'name' => 'name', 'id' => 42]
#=> [{"network"=>"facebook", "picture"=>"picture", "name"=>"name", "id"=>42}]

我猜你想@friend成为一个哈希,并@friends成为一个包含许多 - 哈希的数组friend

于 2013-07-30T00:02:48.087 回答
1

该规范是胡说八道。它有带键的数组和没有键的散列。和对应该交换,键/值对之间应该有逗号{}[]

我认为它看起来像这样

{
  "connections" : [
    {
      "network" : "facebook",
      "picture" : "http://facebook.com/picture.jpg",
      "name" : "User Name",
      "id" : "12345679"
    },
    {
      "network" : "linkedin",
      "picture" : "http://linkedin.com/picture.jpg",
      "name" : "Another User",
      "id" : "959d919sd92"
    }
  ]
}

但我不能确定,你需要回去问这个问题。

于 2013-07-30T22:19:09.980 回答