Send Parameters for Control


Premium Content - Free Preview

Ruby is very flexible, and there are many things you can do in Ruby that are impossible in more restrictive languages.

Ordinary methods

Most methods in classes are instance methods and are called on instances of a class (instead of the class itself). In most cases, you know the name of a method and the number of parameters it takes in, and can call it directly. For example, if you have the following class:

class Dog
    def initialize(name)
        @name = name
    end        

    def greet(person)
        puts "Hi #{person} I'm #{@name}"
    end
end

...you can create a dog, and call the greet method:

doggy = Dog.new("Max")
doggy.greet("Jim")

..which will output:

Hi Jim I'm Max

parameters

Usually, methods take in a specific number of parameters. But you can also create a method that can take in any number of parameters, from 0 and up. You can do this by adding a * at the beginning of the parameter, so multiple parameters can be passed in will be bundled into one array. For example, you can add a new method to the above class for greeting multiple people:

def greet_many(*people)
    people.each {|person| greet(person)}
end

This code uses .each to go through *people and call greet on each person. You can now call greet_many and pass in any number of parameters:

doggy = Dog.new("Max")
doggy.greet_many("Jim", "Sam", "Sarah")

This will output:

Hi Jim I'm Max
Hi Sam I'm Max
Hi Sarah I'm Max

Above, the parameter *people used a * to bundle multiple variables into one array. You can do the reverse when calling a method and use a * to split an array into multiple variables. Given the following method:

def greeter(title, first_name, last_name)
  puts "Hello #{title} #{first_name} #{last_name}"
end

...You can do the following with an array:

person_ar = ["Dr.", "Sarah", "Jones"]
greeter(*person_ar)

This will split person_ar into individual variables, so greeter outputs:


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Comments

Contact Us
Sign in or email us at [email protected]