Rails [ruby on rails] 明明存到 hash 的为一个对象,怎么取出来就是一个 Array 啦

yingjie_xiao · January 31, 2013 · Last by yingjie_xiao replied at February 01, 2013 · 2508 hits

rails 项目中 app/helper/****_helper.rb 这是个 module usertimesheetMap = Hash.new entries.each do |entry| usertimesheet = usertimesheetMap[entry.user.id.to_i] if !usertimesheetMap.has_key?(entry.user.id.to_i) usertimesheet = UserTimesheet.new usertimesheetMap[entry.user.id.to_i] = usertimesheet end usertimesheet = usertimesheetMap[entry.user.id.to_i] custom = CustomValue.new custom = custom.get_custom_value_by_userid(entry.user.id.to_i) usertimesheet.hrid= custom.value.to_s usertimesheet.username= entry.user usertimesheet.project= entry.project

custom = custom.get_location_by_userid(entry.user.id.to_i)

class UserTimesheet

def hrid @hrid end

def hrid=(value) @hrid = value end def username @username end

def username=(value) @username = value end

def CWDays @CWDays end

def CWDays=(value) @CWDays = value end

def NWDays @NWDays end

def NWDays=(value) @NWDays = value end

end

运行结果如下: undefined method `hrid' for #Array:0xb55892b4

usertimesheet.hrid= custom.value.to_s you called hrid on usertimesheet

usertimesheet = usertimesheetMap[entry.user.id.to_i] so usertimesheet is an element in usertimesheetMap.

We know usertimesheetMap is a hash, but not usertimesheet. usertimesheet is probably an array

btw this is not how we name ruby variables.

#1 楼 @blacktulip Thank you inspired me, 问题解决了,我把取值的时候,用法出错了, error: 'usertimesheetMap.each do timesheet'

'end' 哎,这不是 hash 的遍历值的方式,太弱智的错误了

You need to Sign in before reply, if you don't have an account, please Sign up first.