Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Passing Blocks To Methods

Tags:

ruby

highline

I'm trying to do Ruby password input with the Highline gem and since I have the user input the password twice, I'd like to eliminate the duplication on the blocks I'm passing in. For example, a simple version of what I'm doing right now is:

new_pass = ask("Enter your new password: ") { |prompt| prompt.echo = false } verify_pass = ask("Enter again to verify: ") { |prompt| prompt.echo = false } 

And what I'd like to change it to is something like this:

foo = Proc.new { |prompt| prompt.echo = false } new_pass = ask("Enter your new password: ") foo verify_pass = ask("Enter again to verify: ") foo 

Which unfortunately doesn't work. What's the correct way to do this?

like image 459
Chris Bunch Avatar asked Nov 11 '08 17:11

Chris Bunch


People also ask

How do you call blocks in Ruby?

A block is always invoked with a function or can say passed to a method call. To call a block within a method with a value, yield statement is used. Blocks can be called just like methods from inside the method that it is passed to.

What are procs in Ruby?

A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.

How are arguments passed in Ruby?

In Ruby, all arguments are required when you invoke the method. You can't define a method to accept a parameter and call the method without an argument. Additionally, a method defined to accept one parameter will raise an error if called with more than one argument.

What is * args in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).


1 Answers

The code by David will work fine, but this is an easier and shorter solution:

foo = Proc.new { |prompt| prompt.echo = false } new_pass = ask("Enter your new password: ", &foo) verify_pass = ask("Enter again to verify: ", &foo) 

You can also use an ampersand to assign a block to a variable when defining a method:

def ask(msg, &block)   puts block.inspect end 
like image 148
Adam Byrtek Avatar answered Oct 18 '22 13:10

Adam Byrtek