Ruby是一种在条件上执行函数的聪明方法 [英] Ruby a clever way to execute a function on a condition

查看:108
本文介绍了Ruby是一种在条件上执行函数的聪明方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个有趣的项目,我正在Ruby中实现Beatnik解释器。如果您从未听说过Beatnik,那么它就是一种深奥的编程语言,其中的操作由源代码中单词的scrabble score指定。

As a bit of a fun project I'm implementing a Beatnik interpreter in Ruby. If you've never heard of Beatnik it's an esoteric programming language in which operations are specified by the "scrabble score" of the words in the source code.

无论如何,实现需要针对不同的拼字游戏分数进行不同的操作。这不是特别实现的,一个明显的方法是if语句:

Anyway, the implementation requires a different operation to happen for different scrabble scores. This isn't particularly to implement, one obvious ways is an if statement:

if score == 1
...
elsif score == 2
...
else
...
end

另一种方法是使用案例陈述:

Another way would be to use a case statement:

case score
when 1
  ...
when 2
  ...
else
  ...
end

但是这两种方法都不是特别优雅,你能否提出另一种方法来实现这个?

But neither of these two methods strikes me as particularly elegant, can you suggest an alternative way of implementing this?

推荐答案

commands = {
  1 => ->(p1,p2) {...},
  2 => ->(p1,p2) {...},
  3 => ->(p1,p2) {...},
}

commands[score].call(p1,p2)

插入代码代替...,您的参数代替p1,p2。这将创建一个称为命令的哈希,从整数分数到匿名函数( - >是lambda的缩写)。然后根据分数查找相应的功能,并调用它!

Insert your code in place of the ...'s, and your parameters in place of p1,p2. This will create a hash called commands, from integer scores to anonymous functions (-> is short for lambda). Then you look up the appropriate function based on the score, and call it!

这篇关于Ruby是一种在条件上执行函数的聪明方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆