Ruby Array collect 怎么用?

zhangyanan · 2014年01月22日 · 最后由 simlegate 回复于 2014年03月12日 · 2767 次阅读
@sco_array = [#<ExaminationScore:0x10051fe0 @attributes={"student_id"=>"1951", "subject_id"=>"3", "student_name"=>"qqq", "subject_title"=>"英语", "student_code"=>"3101012001320100119", "score"=>"0", "clazz_name"=>"高三(10)班"}>]

想得到 title 是英文的分数,用学生 id 做键,分数做值,怎么实现?

@scores.collect { |s| s.subject_title == '英语' }

请教各位

就是 Arrary.map 的意思,对数组进行处理,你那样得到的结果会是 [true]

想得到title是英文的分数,用学生id做键,分数做值你是要返回一个 Hash 表? collect方法返回的是Array,不是Hash

hash_result = {}
@scores.select { |s| s.subject_title == '英语' }.collect { |s| hash_result[s.student_id] = s.score }

这样是否就满足你的需求了,光一个 collect 搞不定吧?

可以用 Hash[] 把数组转换为 Hash。

Hash[@scores.select { |x| x.subject_title == '英语‘ }.collect { |x| [x.student_id, x.score] }]

传统一点的办法就是用 each 遍历数组时赋值给 hash,我个人倾向于下面这种

hash = {}
@scores.each { |x| hash[x.student_id] = x.score if x.subject_title == '英语' }
@sco_array.inject({}) do |hash, score|
  hash[score.student_id] = score.score if score.subject_title == '英语'
  hash
end

#5 楼 @yonggu

@sco_array.inject({}) do |hash, score|
  hash[score.student_id] = score.score if score.subject_title == '英语'
end

我记得可以这样吧~

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