Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to create a block and pass it as an argument?

Tags:

ruby

I'm working with a method that takes a block as an argument. I'm new to Ruby and Blocks, so I don't quite understand how I would go about creating a Block and passing it to the method. Can you please provide me an example of how you would create a block and pass it as an argument?

Update: Here is an example of the method that I am trying to call:

def exec!(commands, options=nil, &block)
  # method code here
  # eventually it will execute the block if one was passed
end

Here is how I am currently calling this method:

@result = ssh.exec!("cd /some/dir; ls")

How do I pass a block as the third argument to the exec! method?

like image 939
Andrew Avatar asked Oct 11 '11 17:10

Andrew


2 Answers

It depends partially on how you want to use it. An easy way is this, if it fits your usage needs:

@result = ssh.exec!("cd /some/dir; ls") do |something|
    # Whatever you need to do
    # The "something" variable only makes sense if exec! yields something
end

Or

@result = ssh.exec!("cd /some/dir; ls") { |something| puts something }

The {} notation is generally used when the block is short.

You can also create a Proc or lambda; ultimately the "right" answer depends on what you're trying to do.

Note there's an example if you're talking about Net::SSH.

like image 184
Dave Newton Avatar answered Oct 12 '22 11:10

Dave Newton


And one more thing. You can also create Proc-object (or any object that have 'to_proc' method) and call your method with that Proc-object as last argument with '&' symbol before it. For example:

proc = Proc.new { |x| puts x }
%w{1 2 3}.each(&proc)

other way to doing the same thing:

%w{1 2 3}.each { |x| puts x }
like image 21
WarHog Avatar answered Oct 12 '22 13:10

WarHog