Functions


Collapse Content

Functions

Ruby functions are powerful and easy-to-use.

# Basic Function with Parameter    
def double(x)
  x * 2
end

# Functions (and blocks) implicitly return the value of the last statement
double(2) #=> 4

# You can also use an explicit return
def square(x)
   return x * x
end    

# Parentheses are optional where the result is unambiguous
double 3 #=> 6

double double 3 #=> 12

# Multiple Parameters    
def sum(x,y)
  x + y
end

# Method arguments are separated by a comma
sum 3, 4 #=> 7

sum sum(3,4), 5 #=> 12

Yield

All methods have an implicit, optional block parameter which can be called with the 'yield' keyword:

def surround
  puts "{"
  yield
  puts "}"
end

# pass a block in {}
surround { puts 'hello world' }

# output:  
# {
# hello world
# }    

# You can pass a block to a function
# "&" marks a reference to a passed block 
def guests(&block)
 block.call "some_argument" 
end

# You can pass a list of arguments, which will be converted into an array
# That's what splat operator ("*") is for 
def guests(*array)
 array.each { |guest| puts "#{guest}" }
end

Challenge

In Ruby on Rails, pages are created with templates which use the yield statement. The code below passed a block to a template function that still needs to be written.

Create a function below called template that prints the word "start", then yields a block passed to it, and then prints the word "end".

( It shouldn't add any newlines.)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

What will the following code return?

def triple(n)
  n * 3
end

triple triple 2

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

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