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

yingjie_xiao · 2013年01月31日 · 最后由 yingjie_xiao 回复于 2013年02月01日 · 2512 次阅读

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 的遍历值的方式,太弱智的错误了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号