用详细的例子重写问题:
我有三个属性的对象数组,我想构建苛刻的数组,并且得到的哈希没有@name实例属性。我用一个例子模拟了这个问题。
class Employee
attr_accessor :name, :company, :duration
def initialize(name, company, duration)
@name = name
@company = company
@duration = duration
end
end
aSong1 = Employee.new("Fleck", "AMZ", 260)
aSong2 = Employee.new("Taylor", "EMC", 120)
aSong3 = Employee.new("Bob", "Adobe", 260)
aSong4 = Employee.new("Jack", "Google", 360)
final_array = [ ]
final_array.push(aSong1)
final_array.push(aSong2)
final_array.push(aSong3)
final_array.push(aSong4)
puts final_array.length #4
final_array.each do | element |
puts element.is_a?(Object) #true
puts element.name #prints name
end
result = [{company: 'AMZ',duration: 260}, {company: 'EMC',duration: 120},{company: 'Adobe',duration: 260}, {company: 'Google',duration: 360} ]
示例:repl
答案 0 :(得分:0)
您可以使用
删除ID键 a = [{"id":"21","company":"AMC","name":"Matt"},{"id":"22","company":"AMC","name":"Jon"},
{"id":"12","company":"XYZ","name":"Bob"}].each{|o| o.delete :id}
如果你想将它与其他哈希进行比较,你可以使用merge方法,假设a2是第二个哈希
a.merge(a2)
这将返回一个新的哈希值,其中任何匹配的键都会使用第二个哈希值中的新对应值进行更新
答案 1 :(得分:0)
final_array.collect {|x| { company: x.company, duration: x.duration }}
结果:
[{:company=>"AMZ", :duration=>260}, {:company=>"EMC", :duration=>120}, {:company=>"Adobe", :duration=>260}, {:company=>"Google", :duration=>360}]
答案 2 :(得分:0)
以下情况如何?
class Employee
def to_h
instance_variables.each_with_object({}) do |var, h|
k = var.to_s.tr('@','').to_sym
v = instance_variable_get(var)
h[k] = v
end
end
end
result = final_array.map{|e| e.to_h.delete_if{|k,v| k == :name}}