Ruby Functions
# A function is the most basic way we have to reuse code in our programs.
# We can define and call a function as easily as:
def greet(name)
puts "Hi, #{name}!"
end
greet("Rafa")
greet("Xavi")
greet("Isra")
greet("Fernando")
# Also functions can have return values:
def square(number)
return number * number
end
def multiply(a,b)
return a * b
end
puts(square(22))
puts(square(1))
puts(square(10))
puts(multiply(3,2))
puts(multiply(10,3))
# Addition returns the sum of the two numbers
puts 10 + 13
# Similarly, a function can return a result of a custom operation.
# Take a string's reverse function, for example:
puts "desserts".reverse
# Another cool thing you can do in Ruby that is not as easy to do in other
# languages is returning more than one value from a function call:
def power_formula(base_chemical)
sugar = base_chemical * 500
spice = sugar / 1000
everything_nice = sugar / 100
return sugar, spice, everything_nice
end
chemical_x = 10000
blossom, buttercup, bubbles = power_formula(chemical_x)
puts "Using the value #{chemical_x} as our base chemical"
puts "We get values of #{blossom} for blossom, #{buttercup} for buttercup, and #{bubbles} for bubbles."