使用哈希或 case 语句 [Ruby]
一般来说,哪个更好用?:
case n
when 'foo'
result = 'bar'
when 'peanut butter'
result = 'jelly'
when 'stack'
result = 'overflow'
return result
或者
map = {'foo' => 'bar', 'peanut butter' => 'jelly', 'stack' => 'overflow'}
return map[n]
更具体地说,什么时候应该使用 case 语句,什么时候应该简单地使用哈希?
Generally which is better to use?:
case n
when 'foo'
result = 'bar'
when 'peanut butter'
result = 'jelly'
when 'stack'
result = 'overflow'
return result
or
map = {'foo' => 'bar', 'peanut butter' => 'jelly', 'stack' => 'overflow'}
return map[n]
More specifically, when should I use case-statements and when should I simply use a hash?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哈希是一种数据结构,而 case 语句是一种控制结构。
当您只是检索一些数据时(例如您提供的示例),您应该使用哈希。如果需要执行额外的逻辑,则应该编写 case 语句。
另外,如果您需要执行一些模式匹配,那么使用 case 语句是有意义的:
A hash is a data structure, and a case statement is a control structure.
You should use a hash when you are just retrieving some data (like in the example you provided). If there is additional logic that needs to be performed, you should write a case statement.
Also, if you need to perform some pattern matching, it makes sense to use a case statement:
一般来说,编程中的“更好”意味着不同的事情。例如,更好的程序
更好地表达意图
更少的代码行,更少
容易出错等方面
执行时间
内存使用
等。
由于我们谈论的是 Ruby,因此性能通常不太受关注。如果您确实需要性能,您可以考虑另一种编程语言。因此,我首先考虑标准(1)和(2)。更好看的 Ruby 代码通常代表“更好”的程序。哪个代码看起来更好?哪个更能表达意图?如果添加/删除逻辑,哪一个更容易修改?这取决于您的问题,并且在某种程度上这是一个品味问题。
对我来说,在你的简短示例中,哈希解决方案更好。案例解决方案提供了更大的灵活性,在本例中您不需要(但在其他情况下可能需要)。
In general, "better" in programming means different things. For example, better program
expresses the intent better
less lines of code, less
error-prone, etc.
execution time
memory usage
etc.
Since we are talking about Ruby, the performance is typically of a lesser concern. If you really need performance, you might consider another programming language. So, I would look at criteria (1) and (2) first. The better looking Ruby code usually represents a "better" program. Which code looks better? Which expresses the intent better? Which would be easier to modify if you add/remove logic? It depends on your problem, and it's a matter of taste, to certain degree.
To me, in your short example, the hash solution is better. The case solution provides more flexibility, which you don't need in this case (but might need in other cases).
哈希表和 case 语句之间有两个主要区别。
。
这相当于你的代码,在使用 Ruby 或函数式编程语言一段时间后,它对你来说会显得更加自然。它也短得多。
There are two main differences between hash tables and case statements.
.
That's equivalent to your code, and after using Ruby or functional programming languages for a while, it will appear much more natural to you. It's also way shorter.