Monday, February 10, 2014

Default Arguments

I want access to my variables.

There are a number of ways to pass in variables into ruby methods. After my first week at The Flatiron School I initially struggled with passing variable parameters into a function. Within this blog post I will introduce the different ways to pass in variables to a functions.

Required Arguments

def my_method(a, b)
  puts a
  puts b
end

my_method(25, "hello world")
 # => 25
 # => "hello world"

This method may only be called if both a & b are passed in.

my_method(25)
# => "wrong number of arguments (1 for 2)"

If just pass in one method is passed in we will receive the error "wrong number of arguments"

Default Arguments

One to avoid this issue is to pass in a variable as a default argument.

def my_method(a, b="hello world")
  puts a
  puts b
end

In this example b has a default value of "hello, world". If only one variable is passed in this function, will still run.

my_method(25)
# => 25
# => "hello world

Within Other Functions

A third way of getting variables into a function is by saving the variables into another function. I found this useful, if I didn't want to add the same arguments every time.

def add_variable
  hash1 = { :name => thomas, :email => surgentt@gmail.com }
end

def my_method
  add_varable
end

In this example I gain access to the variable hash1 without actually passing it into the function via an argument.


















No comments:

Post a Comment