Most succinct way to randomly choose function to execute?

Suppose I have two function calls to execute, f(x) and g(y). What’s the most succinct way to choose just one of them each time through a loop? I realize I can do this using if or case in conjunction with tick and look, or if it’s the same function with different parameters, I can do

f([x, y].choose)

But I mean the briefest way to do

execute [f(x), g(y)].choose

It probably depends on your code? Do you mean that if f is randomly chosen then it is to be evaluated with argument x, while g will be evaluated with a different argument y?

First of all, it’s eval, not execute, so
eval ["f(x)", "g(y)"].choose
does not seem too verbose. To store a random method for later you could
m = method([:f, :g].choose) ; m.call(z)
or
self.class.send(:alias_method, :h, [:f, :g].choose); h(z)
, among other possibilities; then you really have a “randomly chosen function”

1 Like

Thanks. This quick test:

x = 1
y = 2

live_loop :myloop do
  eval ["puts(x)", "puts(y)"].choose
  sleep 1
end

works as expected. I’d looked through Ruby references, but everything I tried with .call and eval didn’t work. Using an array as an argument to eval—I totally missed that, let alone putting the function calls in quotes.

Another approach is to use lambdas:

x = 1
y = 2

live_loop :my_loop do
  [lambda{puts(x)}, lambda{puts(y)}].choose.call
  sleep 1
end

Of course it’s important to note that all these options rely heavily on Ruby’s functionality which may not always be available in the future if we ever move to hosting the DSL on a different language such as Elixir or Rust.

1 Like