Logo
Section 1 / 10

Ruby中的方法简介

了解 Ruby 中的方法及其重要性。

导入

Ruby中的方法简介

了解 Ruby 中的方法及其重要性。

寻找 num1 的所有因数

puts "请输入第一个数字:" num1 = gets.chomp.to_i divisors_list_1 = [] (1..num1).each do |x| check = num1 % x if check == 0 divisors_list_1 << x end end

寻找 num2 的所有因数

puts "请输入第二个数字:" num2 = gets.chomp.to_i divisors_list_2 = [] (1..num2).each do |x| check = num2 % x divisors_list_2 << x if check == 0 end

定义加法函数

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

调用函数并输出结果

puts add(1, 5) # => 6 puts add(100, 500) # => 600

代码示例

1def f(x) 2 return x**2 - x + 1 3end

趣味数学

通过一种方法求最大公约数