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 { }).
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.
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.
Parameter is the variable in the declaration of the function. Argument is the actual value of this variable that gets passed to the function.
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.
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With