Ruby 哈希返回奇怪的值

Ruby hash returning strange values

我正在返回 JSON 中用户字段的响应。我正在创建 JSON 如下。

def user_response(users)
    users_array = []
    users.each do |user|
      uhash = {}
      uhash[:id] = user.id,
      uhash[:nickname] = user.nickname,
      uhash[:online_sharing] = user.online_sharing,
      uhash[:offline_export] = user.offline_export,
      uhash[:created_at] = user.created_at,
      uhash[:app_opens_count] = user.app_opens_count,
      uhash[:last_activity] = user.last_activity,
      uhash[:activity_goal] = user.activity_goal,
      uhash[:last_activity] = user.last_activity,
      uhash[:region] = user.region
      users_array << uhash
    end
    users_array
  end

但是反应很奇怪。 hash 中的 :id 键有一个包含所有字段的数组,不知道为什么。

{
    "nickname": "adidas",
    "online_sharing": null,
    "offline_export": null,
    "created_at": "2016-08-26T09:03:54.000Z",
    "app_opens_count": 29,
    "last_activity": "2016-08-26T09:13:01.000Z",
    "activity_goal": 3,
    "region": "US",
    "id": [
      9635,
      "adidas",
      null,
      null,
      "2016-08-26T09:03:54.000Z",
      29,
      "2016-08-26T09:13:01.000Z",
      3,
      "2016-08-26T09:13:01.000Z",
      "US"
    ]
  }

那是因为你在每行末尾 ,

每行末尾有逗号,

uhash[:id] = user.id,

另外,您可以将上面的代码改成:

def user_response(users)
  users.map do |user| 
    user.attributes.slice(:id, :nickname, :online_sharing, :offline_export, :created_at, :app_opens_count, :last_activity, :activity_goal, :last_activity, :region)
  end
end

问题由两部分组成:

  1. 一个赋值被赋值为:

    puts (foo = 42) # => prints 42
    
  2. 多个值,在赋值的右侧用逗号分隔形成一个数组:

    bar = 1, 2, 3
    bar # => [1, 2, 3]
    

新行不会改变这一点,因此您基本上可以这样做:

sonne = (foo = :eins), (bar = :zwei), (baz = :drei), (qux = :vier)
sonne # => [:eins, :zwei, :drei, :vier]

修复确实是删除逗号。