[RUBY] 6th

!Ubuntu-20.04.1!ruby-2.7.0p0

variable

Ruby doesn't require type declaration (similar to Python)

name = 'musutafakemaru'
num_i = 1
num_f = 0.1

Try to add using variables

A program that adds two arguments given on the command line

num1 = ARGV[0].to_i #ARGV is a string so cast to int
num2 = ARGV[1].to_i

sum = num1 + num2
puts "#{num1} + #{num2} = #{sum}"

And on the command line

> ruby sum1.rb 1 2

Then

1 + 2 = 3

Was obtained.

Method

This is also a bit like a Python function definition.

def method name(Argument 1,Argument 2)
Process 1
Process 2
・
・
・
end

Unlike Python, indentation has no meaning.

Try to add using the method

Let's create a program created by introducing variables using methods.

def sum (num1, num2)
  sum = num1.to_i + num2.to_i
  puts "#{num1} + #{num2} = #{sum}"
end

sum(ARGV[0], ARGV[1])

On the command line

> ruby sum2.rb 1 2

When you enter

1 + 2 = 3

The output was obtained.

Reference site

This article was created with reference to the following sites.

-Chart type ruby-II (variable and method)


Recommended Posts