Git Product home page Git Product logo

yield-and-return-values's Introduction

Code Along: Yielding and Return Values

Objectives

  1. Understand how to control the return value of a method that uses yield.
  2. Gain more practice with the yield keyword and blocks.
  3. Gain a deeper understanding of the common iterator, #collect.

Why Return Values Matter

Arrays are great for storing lists of information. In the real-world, however, lists change. We might use one list as the basis for collecting information for a different list entirely.

Think about it like this––you are running a popular social networking site and you have a list of a user's posts. Each post has a timestamp. A post might say "posted 10 minutes ago" or "posted 2 days ago". Every few minutes or so, you need to iterate over the list of posts and update the timestamp accordingly.

There are many scenarios in which you will want to iterate over a list of items, make some change to each item, and collect the resulting list of altered items.

This is where controlling the return values of our methods comes in. When we want to iterate over a collection, execute some code using the members of that collection and return the changed collection, we need to find a way to collect the changed items and tell our method to return the new and improved collection.

We already know how to use the yield keyword in a method to pass each successive element of a collection to a block of code. Now, let's take a closer look at using yield and capturing the return value of the code block that we will call with such a method.

Yield and Return Values

This is a code-along exercise. NOTE: There are NO tests in this lab. If you run learn test, you might see the following message in your terminal: This directory doesn't appear to have any specs in it. That's ok!

We've given you some code in lib/practicing_returns.rb that we will build on together throughout the course of this reading.

Each time you use yield(some_argument) in the body of a method, it passes some_argument to the block you call that method with. Open up lib/practicing_returns.rb and take a look at the following code:

def hello(array)
  i = 0
  while i < array.length
    yield(array[i])
    i += 1
  end
end

In this method, we are using a while loop to iterate over an array and yielding each member of the array in turn to a block.

We would call our method like this:

hello(["Tim", "Tom", "Jim"]) { |name| puts "Hi, #{name}" }

Which would output to the terminal:

# > Hi, Tim
# > Hi, Tom
# > Hi, Jim

You can run this file in your terminal with ruby lib/practicing_returns.rb to see for yourself.

What is the return value of this method call, though?

Let's find out! Notice that we have required Pry for you at the top of lib/practicing_returns.rb Go ahead and place a binding.pry on line 11, just before we call our #hello method.

Run the file with ruby lib/practicing_returns.rb in your terminal. We should be dropped right into our binding.

Inside the Pry console in your terminal, manually invoke the method by copying and pasting the following and hitting enter:

hello(["Tim", "Tom", "Jim"]) { |name| puts "Hi, #{name}" }

You should see the following:

# > Hi, Tim
# > Hi, Tom
# > Hi, Jim
=> nil

Notice that our method puts-ed out the code we expected and returned nil. Why is that?

That is because the return value of a while loop is always nil. If we want our method to return something else, we have to tell it to do so.

Let's tell our method to return a new array of strings that contain the above greetings, instead of simply puts-ing out our greetings.

We can capture the return value of the code that is executed when yield passes a value to a block.

Capturing the Return Value of Using Yield

Make the following change to the code block that we are calling with our #hello method in lib/practicing_returns.rb:

hello(["Tim", "Tom", "Jim"]) { |name| "Hi, #{name}" }

Now, the return value of each execution of the code in our block will be a string: "Hi, #{name}".

Let's take a look at capturing the return value of yielding to this block.

Place a binding.pry:

def hello(array)
  i = 0
  while i < array.length
    binding.pry
    yield(array[i])
    i += 1
  end
end

Now, run the file with ruby lib/practicing_returns.rb. You should be dropped right into your binding. Let's manually execute our yield so that we can see the return value. In the Pry console in your terminal:

yield(array[i])

This returns:

"Hi, Tim"

Here, we are looking at the return value of our block's execution with the yielded value of array[i], which at this point in our iteration is equal to "Tim".

Now that we understand that calling yield(some_argument) will give us the return value of the execution of the block with that argument, we can capture those return values.

def hello(array)
  i = 0
  collection = []
  while i < array.length
    collection << yield(array[i])
    i += 1
  end
end

Here we are setting a variable, collection, equal to an empty array. Then, inside our while loop, we push the return value of using yield(array[i]) into that collection array.

Lastly, we need to return that new collection at the end of our method:

def hello(array)
  i = 0
  collection = []
  while i < array.length
    collection << yield(array[i])
    i += 1
  end
  collection
end

And that's it! We've successfully built our own iteration using a while loop, yielded each individual member of an array to a block and captured the return values of yielding those items to the block. This is exactly how the #collect method works, and we've just built it out, all by ourselves.

yield-and-return-values's People

Contributors

annjohn avatar dakotalmartinez avatar ihollander avatar itsjustarepo avatar maxwellbenton avatar sophiedebenedetto avatar tmtarpinian avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yield-and-return-values's Issues

Suggested Improvement

While this learn along lab is trying to show return values originating from using yield blocks, essentially the example doesn't do anything of that sort. Despite creating a "collections" array, and trying to store return values from yield into the collections block, leaving the "hello" method's block same, does not yield any return value anyways. The final "collections" array is still an empty array with three "nil"s. Conceptually, it could have been better explained by changing the block to actually give a return value which would be collected in the "collections" array rather than "nil"
screen shot 2016-09-12 at 9 52 46 pm

Lab lack rpec files for testing

Although the lab asks students to run this lab following the specs, there are no rspec files in the respository to do so.
Thank you!

File names inconsistent

The file to be run is called by different names:

ruby lib/practicing_returns.rb
lib/practicing_ruby.rb
ruby lib/practicing_yield.rb

Only the first file is available.

Cant test or submit

The codes aren't acting the way is said it would in the description. Maybe I'm doing something wrong but not sure.

Also don't know how to submit as learn submit doesn't yield any result.

My Spec file is missing

I keep deleting the repository but it is not resetting my file for me to complete this lab

The lesson needs to specify certain things

If rspec expects specific terms to be used, such "my_collect" or "languages", the lesson should state it as such. Otherwise, a student ends up spending a lot of time tweaking code, only to discover it's the array name that needed to be changed.

No spec, cannot submit

This lesson requires you to open, submit work, and complete work, however running "learn" just comes with "This directory does not appear to have any specs in it.". It doesn't even register the fact that I opened the ide.
image

Return from Yield Statement

Hi! I need help running this test and submit the test.

This is the error message I got.

[07:06:00] (master) yield-and-return-values-online-web-sp-000
// ♥ learn
This directory doesn't appear to have any specs in it.
[07:09:35] (master) yield-and-return-values-online-web-sp-000
// ♥

Broken lab

The Return From Yield Statements lab doesn't work. It returns nil as written. The whole collection array is unnecessary. Here is what I did - I don't know if it's the best way but it works and is much simpler than the method in the lesson which doesn't actually work.

def hello(array)
i = 0
while i < array.length
yield(array[i])
i += 1
end
array
end

hello(["Tim", "Tom", "Jim"]) do |name|
puts "Hi, #{name}"
name
end

The key way explicitly returning name from the yield. You can add it to a collection array if you want but you don't need to. All the explanation is wrong too given that it presents as fact something that doesn't work. I hope this helps! Best, Nancy

Not letting me mark as complete

This lab isn't letting me mark as complete since there are no specs. "Submit pull requests" isn't highlighting and it won't let me do "learn submit"

Missing spec file

IDE in this lesson has no spec file in it's directory, therefore I'm unable to submit my task.

No spec file

Trying to use "learn" to run file and drop into Pry but lab doesn't have spec files.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.