昊天SEO

练习21: 函式的返回值–笨方法学ruby在线

你已经学过使用=给变量命名,以及将变量定义为某个数字换字符串。接下来我们将让你见证更多奇迹。我们要示范给你的是如何使用=来将变量设置为「一个函式的值」。有一件事你需要特别注意,但待会再说,先输入下面的脚本吧:

def add(a, b)
  puts "ADDING #{a} + #{b}"
  a + b
end

def subtract(a, b)
  puts "SUBTRACTING #{a} - #{b}"
  a - b
end

def multiply(a, b)
  puts "MULTIPLYING #{a} * #{b}"
  a * b
end

def divide(a, b)
  puts "DIVIDING #{a} / #{b}"
  a / b
end

puts "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78,4)
weight = multiply(90, 2)
iq = divide(100, 2)

puts "Age: #{age}, Height: #{height}, Weight: #{weight}, IQ: #{iq}"

# A puzzle for the extra credit, type it in anyway.
puts "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

puts "That becomes: #{what} Can you do it by hand?"

本文地址官网    新乡网站建设,seo

分享到:更多 ()