注意数组差异 - Ruby
问题描述:
我有两个数组。一个是一组技能,另一个是用户可以做的一套技能。为了说明:注意数组差异 - Ruby
['swimming', 'rowing', 'cycling'] is the set of all skills
现在,用户可以拥有一套像技巧:
['rowing', 'cycling']
如何创建一个漂亮的哈希将呈现一个用户是否有目前的技术?对于这个特定的用户,它将是:
{'swimming' => no, 'rowing' => yes, 'cycling', => yes}
P.S.我其实想用轨道中的活动记录对象来做到这一点,但我想这是同一个想法。
答
下面将为true
和false
代替yes
和no
。
all_skills = %w[swimming rowing cycling]
user_skills = %w[rowing cycling]
Hash[all_skills.map{|k| [k, user_skills.include?(k)]}]
,或者,如果你不介意nil
,而不是为no
情况下,下面是快。
Hash[user_skills.map{|k| [k, true]}]}
答
这里有一个简洁的方式来做到这一点:
ALL_SPORTS = ['swimming', 'rowing', 'cycling']
user_array = ['rowing', 'cycling']
user_hash = ALL_SPORTS.inject(Hash.new) { |h, sport| {sport => user_array.include?(sport)}.merge(h) }
答
我假设当你说'是'和'否'你真的想要布尔值。以下不使用任何中间值,仅依赖于用户的定义运动:
> h = Hash.new(false).merge(Hash[%w[rowing swimming].map {|v| [v.to_sym, true]}])
=> {:rowing=>true, :swimming=>true}
现在,如果你调用任何其他运动的一个关键是,用户没有你得到期望的结果:
> h[:golf]
=> false
这也假设你也需要键的符号。