Ruby Return Values

I get back the same value I put in, even though I tried to change the data?Turns out, every method in ruby returns an object.

One object.

If nothing has been explicitly returned, i.

e.

the return keyword is not used in a method (return is hardly ever used in Ruby), then a method returns the last line executed.

For example :> def add_two(num)> num + 2> endWhen called:> add_two(6)=>8The add_two return value is the last line executed in the method.

But wait, if I go back to my say_hello method, I see the last line executed is puts “Hello World”, but my return value is still nil?.This is because the puts method was designed to do one thing only: print an argument to the console.

It will not and will never have a return value, because that’s just the way puts was created.

Going back to the previous each iteration, I see that I have obviously executed a line of ruby that is not reflected in my return value.

> array = [1, 2, 3]> array.

each do |num|> num * 2end=> [1, 2, 3]Ruby totally ignored my num * 2 operation!.Not cool.

Turns out, the each iterator is just that: an iterator.

Nothing fancy.

Each is used to go from one element to the next in an array, and that’s about it.

This is beneficial when we need to access an array’s data without trying to manipulate that data.

> array = [1, 2, 3]> array.

each do |num|> puts num> end123=>[1, 2, 3]Each was used to jump from element to element, simply putsing to the terminal each element, and the original array is returned.

What’s the significance of a return value?.What’s the point?.A return value allows a programmer to work off the method being called.

For example:> num = 8> num.

even?> trueThe method even?.is called and returns a boolean: true or false.

I can write more code based on the return value of even?> num = 8> if num.

even?> puts "I have an even number!"> else> puts "I have an odd number!"> endI have an even number!=>nilI was able to build off the return value of even?!.Pretty cool, if you ask me!.If I want to get a bit more complicated, I can set a variable equal to a method and use that variable somewhere in my code!.The value of the variable will equal the return value of its corresponding method.

For example:> def add_two(num)> num + 2> end=> :add_two #this is just showing that I've built a method>> def multiply_two(num)> num * 2> end=> :multiply_two>> new_number = add_two(2)=>4> multiply_two(new_number)=>8Return values become easier to understand over time and allow a programmer to build methods off other methods; they are practical, convenient, and extremely useful.

Going forward, I hope you are able to understand the importance of return values and the role they play in Ruby.

.

. More details

Leave a Reply