About Ruby methods

Programming study diary

July 10, 2020 Progate Lv.165 RubyⅢ

What is a method

A collection of multiple processes into one. You can create (= define) a method by writing the process you want to put together between the def method name and ʻend`. The method is called by writing the method name.

index.rb


def introduce
  puts "Hello World"
end
#Method call
introduce

console


Hello World

argument

The argument is like adding information to the method. Arguments can be specified with def method name (argument). To call a method by passing an argument, use method name (value).

index.rb


def introduce(name)
  puts "Hello"
  puts "#{name}is"
end
introduce("Tanaka")
introduce("Yamamoto")

console


Hello
I'm Tanaka
Hello
I'm Yamamoto

* Methods with arguments cannot be called without passing arguments </ font>

Multiple arguments

You can use multiple arguments by arranging the arguments received in parentheses separated by commas ,. From the left, they are called the first argument and the second argument.

index.rb


def introduce(name, age)
  puts "#{name}is"
  puts "#{age}I'm old"
end
introduce("Tanaka",17)

Method scope

The scope is the range in which the variable can be used. The arguments prepared when defining a method can only be used inside that method (def ~ end). Variables defined in a method can only be used in that method (def ~ end).

Return value

The processing result received by the caller is called the return value, and this is called "the method returns the return value". You can receive the value at the caller by using return in the method. return not only returns a return value, but also has the property of terminating the method. </ font>

index.rb


def add(a, b)
  #a+The value of b returns to the caller as the return value
  return a+b
end
sum=add(1, 3)
puts sum

console


4

The return value can also be a boolean value. In this case, add ? to the end of the method name.

index.rb


def negative?(number)
  return number<0
end
puts negative?(5)

console


false

Keyword arguments

If the value of the argument becomes large, it becomes difficult for the caller to understand, so specify the argument on the caller with the keyword argument. In addition to the normal method, (1) add a colon after the argument on the constant side, and (2) write the argument name before the value on the caller side. By doing these two points, you can write a method with keyword arguments.

index.rb


def introduce(name:, age:, height:)
  puts "I#{name}is"
  puts "#{age}I'm old"
  puts "How tall are you#{height}cm"
end
introduce(name:"Tanaka", age:17, height:176)

console


I'm Tanaka
I am 17
It's 176 cm

Recommended Posts