Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails optional argument

I have a class

class Person     attr_accessor :name,:age     def initialize(name,age)         @name = name         @age = age     end end 

I'd like to make the age optional so its 0 if its not passed, or the name to be blank if not passed

Ive researched a bit on it but its a bit confusing as to what i've found (having to pass variables in another variable { }).

like image 304
Tarang Avatar asked Mar 14 '12 21:03

Tarang


People also ask

How do you pass an argument in Ruby?

How to Use Command-Line Arguments. In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV special variable. ARGV is an Array variable which holds, as strings, each argument passed by the shell.

What is a Ruby argument?

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's the difference between a parameter and an argument Ruby?

Parameter is the variable in the declaration of the function. Argument is the actual value of this variable that gets passed to the function.

What is &Block in Ruby?

The &block is a way of sending a piece of Ruby code in to a method and then evaluating that code in the scope of that method. In your example code above it means a partial named cart will be rendered in a div.


1 Answers

It's as simple as this:

class Person     attr_accessor :name, :age      def initialize(name = '', age = 0)         self.name = name         self.age = age     end end   Person.new('Ivan', 20) Person.new('Ivan') 

However, if you want to pass only age, the call would look pretty ugly, because you have to supply blank string for name anyway:

Person.new('', 20) 

To avoid this, there's an idiomatic way in Ruby world: options parameter.

class Person     attr_accessor :name, :age      def initialize(options = {})         self.name = options[:name] || ''         self.age = options[:age] || 0     end end  Person.new(name: 'Ivan', age: 20) Person.new(age: 20) Person.new(name: 'Ivan') 

You can put some required parameters first, and shove all the optional ones into options.

Edit

It seems that Ruby 2.0 will support real named arguments.

def example(foo: 0, bar: 1, grill: "pork chops")   puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}" end  # Note that -foo is omitted and -grill precedes -bar example(grill: "lamb kebab", bar: 3.14) 
like image 153
Sergio Tulentsev Avatar answered Sep 18 '22 19:09

Sergio Tulentsev