ruby 中的条件链接 [英] conditional chaining in ruby

查看:36
本文介绍了ruby 中的条件链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中有条件地链接方法的好方法吗?

Is there a good way to chain methods conditionally in Ruby?

我想做的功能是

if a && b && c
 my_object.some_method_because_of_a.some_method_because_of_b.some_method_because_of_c
elsif a && b && !c
 my_object.some_method_because_of_a.some_method_because_of_b
elsif a && !b && c
 my_object.some_method_because_of_a.some_method_because_of_c

etc...

因此,根据一些条件,我想确定在方法链中调用哪些方法.

So depending on a number of conditions I want to work out what methods to call in the method chain.

到目前为止,我以好方法"做到这一点的最佳尝试是有条件地构建方法字符串,并使用 eval,但肯定有更好、更红宝石的方法吗?

So far my best attempt to do this in a "good way" is to conditionally build the string of methods, and use eval, but surely there is a better, more ruby, way?

推荐答案

你可以把你的方法放到一个 arry 中,然后执行这个数组中的所有内容

You could put your methods into an arry and then execute everything in this array

l= []
l << :method_a if a
l << :method_b if b
l << :method_c if c

l.inject(object) { |obj, method| obj.send(method) }

Object#send 执行给定名称的方法.Enumerable#inject 遍历数组,同时为块提供最后返回的值和当前数组项.

Object#send executes the method with the given name. Enumerable#inject iterates over the array, while giving the block the last returned value and the current array item.

如果你想让你的方法接受参数,你也可以这样做

If you want your method to take arguments you could also do it this way

l= []
l << [:method_a, arg_a1, arg_a2] if a
l << [:method_b, arg_b1] if b
l << [:method_c, arg_c1, arg_c2, arg_c3] if c

l.inject(object) { |obj, method_and_args| obj.send(*method_and_args) }

这篇关于ruby 中的条件链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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