(Hackerrank) Ruby - 可枚举 - group_by 如果条件有问题

(Hackerrank) Ruby - Enumerable - group_by if condition problem

我只是想解决这个问题。 (https://www.hackerrank.com/challenges/ruby-enumerable-group-by/problem?isFullScreen=true&h_r=next-challenge&h_v=zen)

我的解决方案适用于 ruby 我的,但如果条件不起作用,则首先适用于 hackerrank。

def group_by_marks(marks, pass_marks)
  all_students = Hash.new
  failed = Array.new
  passed = Array.new

  marks.each do |student|

    if student[1] < pass_marks
      failed.push(student)
    elsif student[1] > pass_marks
      passed.push(student)
    end

  end
  all_students["Failed"] = failed
  all_students["Passed"] = passed
  puts all_students
end

问题陈述包含此 If a particular key is empty, don't return that key

此外,您需要删除 puts,因为您需要 return 它,all_studentsreturn all_students 相同,因为 ruby returns自动最后一行。

因此您需要使用以下内容更新最后 3 行。

  all_students["Failed"] = failed if failed.any?
  all_students["Passed"] = passed if passed.any?
  all_students