在Ruby中的其他方法中使用参数传递方法

时间:2021-11-28 23:17:49

I'm interesting how to pass method with arguments in ruby. I need to implement something like command pattern with flexible function setting. Example => lambda functions in C#.

我很有趣如何在ruby中传递带参数的方法。我需要实现像命令模式这样灵活的功能设置。 Example => C#中的lambda函数。

3 个解决方案

#1


2  

Ruby lambda functions are defined as follows:

Ruby lambda函数定义如下:

  a.lambda{ puts "Hello"}
  a.call #=> Hello

  a = lambda{|str| puts str }
  a.call("Hello world !!!") #=> Hello world !!!

  a = lambda{|*args| puts args.join(' ')}
  a.call("Hello", "World") #=> Hello World

#2


1  

You could do the command pattern the way you do most things in Ruby: with a block.

您可以像在Ruby中执行大多数操作一样执行命令模式:使用块。

class Soldier

  def initialize(&block)
    @command = block
  end
  def action
    @command.call if @command
  end

end

s = Soldier.new do #the block
  line = "We are drill machines, drill machines feel no pain"
  2.times{ puts line }
  puts line.upcase
end

puts "Action:"
s.action

#3


0  

You can dynamically invoke methods along with their argument lists. Below is only one of the ways

您可以动态调用方法及其参数列表。以下只是其中一种方式

class Foo
  def foo(what)
    puts what
  end
end

Foo.new.send(:what, "something")  # ==> "something"

#1


2  

Ruby lambda functions are defined as follows:

Ruby lambda函数定义如下:

  a.lambda{ puts "Hello"}
  a.call #=> Hello

  a = lambda{|str| puts str }
  a.call("Hello world !!!") #=> Hello world !!!

  a = lambda{|*args| puts args.join(' ')}
  a.call("Hello", "World") #=> Hello World

#2


1  

You could do the command pattern the way you do most things in Ruby: with a block.

您可以像在Ruby中执行大多数操作一样执行命令模式:使用块。

class Soldier

  def initialize(&block)
    @command = block
  end
  def action
    @command.call if @command
  end

end

s = Soldier.new do #the block
  line = "We are drill machines, drill machines feel no pain"
  2.times{ puts line }
  puts line.upcase
end

puts "Action:"
s.action

#3


0  

You can dynamically invoke methods along with their argument lists. Below is only one of the ways

您可以动态调用方法及其参数列表。以下只是其中一种方式

class Foo
  def foo(what)
    puts what
  end
end

Foo.new.send(:what, "something")  # ==> "something"