Exercise 21. Functions Can Return Something

Image

You have been using the = character to name variables and set them to numbers or strings. We’re now going to blow your mind again by showing you how to use = and a new Ruby word return to set variables to be a value from a function. There will be one thing to pay close attention to, but first type this in:

ex21.rb

 1    def add(a, b)  2      puts "ADDING #{a} + #{b}"  3      return a + b  4    end  5  6    def subtract(a, b)  7      puts "SUBTRACTING #{a} - #{b}"  8      return a - b  9    end 10 11    def multiply(a, b) 12      puts "MULTIPLYING #{a} * #{b}" 13      

Get Learn Ruby the Hard Way: A Simple and Idiomatic Introduction to the Imaginative World of Computational Thinking with Code, Third Edition, Video Enhanced Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.