【问题标题】:Is there a way to call methods of a specific class randomly in ruby?有没有办法在 ruby​​ 中随机调用特定类的方法?
【发布时间】:2017-12-04 12:50:24
【问题描述】:

我想知道是否可以这样做:

class Something
  def A
    puts "A"
  end
  def B
    puts "B"
  end
  def C
    puts "C"
  end
  def D
    puts "D"
  end
end

y = Something.new
x = Random.new
x.rand(y)

然后得到“Something”类的随机结果

【问题讨论】:

  • 您可以将方法放入一个列表中,然后从列表中随机选择一个。

标签: ruby class random methods


【解决方案1】:
class Random
 def rand_method
  #instance_methods(false), gives methods as symbols that are only inside of Something
  Something.instance_methods(false).sample
 end
end


Random.new.rand_method # will give the random method

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
【解决方案2】:

单行答案是:

Something.new.send(Something.instance_methods(false).shuffle.first)

解释

Something.instance_methods(false)
# Will give you [:A, :B, :C, :D]

Something.instance_methods(false).shuffle.first
# Will give you a random method out of it

Something.new.send(<method name>)
# Will call that random method and give you output

来自评论(一个很好的建议)

你可以像这样使用它:

Something.instance_methods(false).sample 而不是Something.instance_methods(false).shuffle.first

【讨论】:

  • 使用sample 而不是shuffle.first
  • 另外,对于公共方法,请始终使用public_send 而不是send
  • 您也可以使用实例,即s = Something.new ; s.send(s.public_methods(false).sample)
  • @CarySwoveland Aaa..我很困惑! :-(
  • 当我读到(原文如此)“这是一个单行字。”,然后是(得到这个)一行代码时,我总是很开心。就好像读者可能认为它实际上是几行代码,“这是我的答案。”。如果作者真的意思是“这是我的答案,我很聪明,可以用一行代码表达出来”,我只能说我读过很多单行代码明显不如多行代码的解决方案或者完全错了。
【解决方案3】:

如果你真的想这样做 -

x.send(x.instance_methods(false).sample, y)

当然,如果目标方法不接受参数,这将不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 2019-11-30
    • 2022-11-07
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多