首页 > 解决方案 > 如何从哈希数组中提取

问题描述

people = [
    {id: 101, first_name: 'John', last_name: 'Doe'},
    {id: 102, first_name: 'Tom', last_name: 'Rogers'},
    {id: 103, first_name: 'Bill', last_name: ''}
]

我想放一个这样的名字列表

"John Doe, Tom Rogers, Bill"

我怎样才能在红宝石中实现这一点?

标签: ruby

解决方案


输入

people = [
  { id: 101, first_name: 'John', last_name: 'Doe' },
  { id: 102, first_name: 'Tom', last_name: 'Rogers' },
  { id: 103, first_name: 'Bill', last_name: '' }
]

代码

p people.map { |x| x[:first_name].to_s + ' ' + x[:last_name].to_s }
        .map(&:strip)
        .join(",")

输出

"John Doe,Tom Rogers,Bill"

推荐阅读