这就是在 Ruby 中测试使用块的函数的方式吗?

发布于 2024-11-07 08:05:32 字数 735 浏览 0 评论 0原文

我有一个函数,它给定一组学生及其成绩,进行分类:

students = {"Good student":"A","Bad Student":"D","Average student":"C"}
student_cat = ["Best","So-so","Below average"]

我的函数是这样工作的:

categorize(students,student_cat) do |s,g|
   # s would be "Good student" and g would be "Best"
   # s would be "Bad student" and g would be "Below average"
   # s would be "Average student" and g would be "So-so"
end

现在我正在这样测试它:

  categorize(students,student_cat) do |s,g|
       assert g == "Best" if s == "Good student"
       assert g == "Below average" if s == "Bad student"
       assert g == "So-so" if s == "Average student"
  end

是否有另一种测试函数以块作为参数的方法?这是一个足够好的方法吗?

I have a function which given a set of students and their grades, makes a categorization:

students = {"Good student":"A","Bad Student":"D","Average student":"C"}
student_cat = ["Best","So-so","Below average"]

And my function works like this:

categorize(students,student_cat) do |s,g|
   # s would be "Good student" and g would be "Best"
   # s would be "Bad student" and g would be "Below average"
   # s would be "Average student" and g would be "So-so"
end

Right now I'm testing it like this:

  categorize(students,student_cat) do |s,g|
       assert g == "Best" if s == "Good student"
       assert g == "Below average" if s == "Bad student"
       assert g == "So-so" if s == "Average student"
  end

Is there another way of testing functions take blocks as parameters? Is this a good enough way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟火散人牵绊 2024-11-14 08:05:32

这样就可以了。不过,如果您使用块来收集结果,然后断言整个结果,则可以使测试更加严格一些:

results = []
categorize(students,student_cat) do |s,g|
  results << [s, g]
end
assert results == [
  ["Good student", "Best"],
  ["Bad Student", "Below average"],
  ["Average student", "So-so"],
]

这样该函数就不会在正确的结果中产生一些无意义的内容,并且不会被发现。

如果函数可以按任何顺序返回其结果,则在比较之前对结果进行排序:

assert results.sort == [
  ["Average student", "So-so"],
  ["Bad Student", "Below average"],
  ["Good student", "Best"],
]

That'll work fine. You can make the test a little more strict, though, if you use the block to collect the results, and then assert the entire result:

results = []
categorize(students,student_cat) do |s,g|
  results << [s, g]
end
assert results == [
  ["Good student", "Best"],
  ["Bad Student", "Below average"],
  ["Average student", "So-so"],
]

That way the function can't yield some nonsense along with the proper results and have it go undetected.

If the function may return its results in any order, then sort results before comparing it:

assert results.sort == [
  ["Average student", "So-so"],
  ["Bad Student", "Below average"],
  ["Good student", "Best"],
]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文