Method in Ruby

2020-08-26 hit count image

Let's see how to use Method(Function) in Ruby.

Outline

The Method(Function) is used to define the process in the program, and call when necessary. In this blog post, we will see how to use the Method in Ruby.

Define

You can define the Method like below.

def add(a, b)
  x = a + b
  return x
end

puts add(1, 2)

# 3

Return

You can omit the last return of the Method.

def add(a, b)
  x = a + b
end

puts add(1, 2)

# 3

If the last return is omitted, the last variable is returned automatically.

Bracket

You can omit the bracket if the parameter does not exist.

def print
  puts 'Hello'
end

print

# Hello

Parameter

Parameter’s default

You can set the Parameter’s default like below.

def add(a, b = 2)
  x = a + b
end

puts add(1)

# 3

Block parameter

You can send the Block(process group) to the Method via the parameter with & character like below.

def temp(&a)
  a.call
end

temp {
  puts "Hello"
  puts "World"
}

# Hello
# World

To execute the block, you should use the call method.

def temp(&a)
  a.call
end

temp do
  puts 'Hello'
  puts 'World'
end

# Hello
# World

Variable length parameter

You can use the variable-length parameter with * character like below.

def temp(num, *n)
  puts num
  puts n
end

temp(1, 2, 3)
puts '------------'
temp(1, 2, 3, 4, 5)

# 1
# 2
# 3
# ------------
# 1
# 2
# 3
# 4
# 5

undef and defined

undef

You can cancel the defined Method by undef.

def temp
  puts 'Hello'
end

temp
undef temp
temp

# Hello
# Traceback (most recent call last):
# temp.rb:9:in `<main>': undefined local variable or method `temp' for main:Object (NameError)

defined

You can check the Method exists or not by defined.

def temp
  puts 'Hello'
end

puts defined? temp
undef temp
puts defined? temp

# method
#

When you use defined, you can see the string indicating the kind of expression defined like below.

# super
# method
# yield
# self
# nil
# true
# false
# assignment
# local-variable
# local-variable(in-block)
# global-bariable
# instance-variable
# constant
# class variable
# $&
# $`
# $1
# $2
# expression

Completed

We’ve seen how to define and use the Method in Ruby. Also, we’ve seen Ruby’s unique feature. Let’s define the Method and use it in Ruby!

Posts