Ruby 1.9:将这4个数组转换为键/值对的哈希值

时间:2010-05-06 00:48:50

标签: ruby

我有四个从客户端进来的数组。假设有一系列名称,出生日期,喜欢的颜色和位置。我的想法是我想要一个哈希,其中每个名称都有一个具有相应属性的哈希:

来自客户的示例日期:

[name0, name1, name2, name3]
[loc0, loc1]
[favcololor0, favcolor1]
[bd0, bd1, bd2, bd3, bd4, bd5]

输出我想实现:

name0 => { location => loc0, favcolor => favcolor0, bd => bd0 }
name1 => { location => loc1, favcolor => favcolor1, bd => bd1 }
name2 => { location => nil, favcolor => nil, bd => bd2 }
name3 => { location => nil, favcolor => nil, bd => bd3 }

我希望在一天结束时有一个数组,我可以迭代并处理每个特定的人哈希。

每个数组中不需要有相同数量的值。意思是,名字是必需的..我可能会收到5个,但我只能收到3个出生日期,2个最喜欢的颜色和1个位置。每个缺失值都将导致零。

如何使用Ruby 1.9制作这种数据结构?

3 个答案:

答案 0 :(得分:2)

我可能会这样做

# assuming names, fav_colors, birth_dates, and locations are your arrays

name_collection = {}

names.zip(birth_dates, fav_colors, locations) do |name, birth_date, fav_color, location|
  name_collection[name] = { :birth_date => birth_date,
                            :fav_color => fav_color,
                            :location => location }
end

# usage
puts name_collection['jack'][:fav_color] # => 'blue'

答案 1 :(得分:0)

代表一个人的小班

class Person
  attr_accessor :name, :color, :loc, :bd

  def initialize(args = {})
    @name = args[:name]
    @color = args[:color]
    @loc = args[:loc]
    @bd = args[:bd]
  end

  def pp()
    puts "*********"
    puts "Name: #{@name}"
    puts "Location: #{@loc}"
    puts "Birthday: #{@bd}"
    puts "Fav. Color: #{@color}"
    puts "*********"
  end
end
另一个代表人的人,主要是人员列表。

class People
  attr_accessor :list_of_people

  def initialize()
    @list_of_people = {}
  end

  def load_people(names, locations, favcolors, birthdates)
    names.each_with_index do |name, index|
      @list_of_people[name] = Person.new(:name => name, :color => favcolors[index], :loc => locations[index], :bd => birthdates[index])
    end
  end

  def pp()
    @list_of_people.each_pair do |key, value|
      value.pp()
    end

  end
end

我为每个人提供了一个漂亮的打印功能,以便您可以看到他们的数据。有了这样的起点,修改和添加各种有用的方法将非常容易。

if __FILE__ == $0
  names = ["name0", "name1", "name2", "name3"]
  locs = ["loc0","loc1"]
  favcolors = ["favcolor0", "favcolor1"]
  bds = ["bd0","bd1","bd2","bd3","bd4"]

  a = People.new()
  a.load_people(names,locs,favcolors,bds)
  a.pp()
end

答案 2 :(得分:0)

我认为您正在寻找的数据结构类型是-ahem- a Struct。

    # setup data
    names = %w(name0 name1 name2 name3)
    locations = %w(loc0 loc1)
    colors = %w(favcololor0 favcolor1)
    bd = %w(bd0 bd1 bd2 bd3 bd4 bd5)

    # let's go
    Person = Struct.new( :name, :location, :fav_color, :bd )
    all_persons = names.zip( locations, colors, bd ).map{|p| Person.new( *p)}
    # done

    puts all_persons
    someone= all_persons.find{|p| p.name == "name1"}
    puts someone.location unless someone.nil?