Code Monkey home page Code Monkey logo

interpolation-super-power's Introduction

Interpolation Super Power

Objectives

  1. Interpolate arbitrary code into a string
  2. Interpolate elements of an array into a single string

Overview

We've talked about string interpolation, but let's review quickly. String interpolation allows us to evaluate Ruby code, and inject the return value into the middle of a string. Normally, we see something like this:

name = "Bob"

puts "Hello, #{name}"

# => "Hello, Bob"

We're not just limited to injecting simple variables, though. We can do slightly fancier things if we just think of the pound sign/curly braces (#{}) as delimiters that allow us to run arbitrary code in the middle of a string. For example, there is nothing preventing us from doing something like this:

puts "1 plus 1 is #{1 + 1}!"

# => "1 plus 1 is 2!"

Almost anything is fair game here. In fact, we're not even limited to just one interpolation per string. It's perfectly acceptable for me to do the following:

three = 2 + 1
name  = "Bob"

puts "1 plus 1 is #{1 + 1} and 1 plus 2 is #{three} and 2 times 2 is
#{2 * 2}. Oh, hey #{name}!"

# => "1 plus 1 is 2 and 1 plus 2 is 3 and 2 times 2 is 4. Oh, hey Bob!"

This means we can do some pretty awesome stuff! Let's say we wanted to print out a business card for our friend, Bob. We want it to look like this:

# => "Name: Bob, Age: 46, Occupation: Juggler"

At first blush, it might make sense to do something like this:

name       = "Bob"
age        = 46
occupation = "Juggler"

puts "Name: #{name}, Age: #{age}, Occupation: #{occupation}"

# => "Name: Bob, Age: 46, Occupation: Juggler"

But what if, now, we also want to print a business card for Stefani? With this pattern, we'd need to start creating a whole bunch of variables:

bob_name           = "Bob"
bob_age            = 46
bob_occupation     = "Juggler"
stefani_name       = "Stefani"
stefani_age        = 49
stefani_occupation = "Firefighter"

puts "Name: #{bob_name}, Age: #{bob_age}, Occupation: #{bob_occupation}"

# => "Name: Bob, Age: 46, Occupation: Juggler"

puts "Name: #{stefani_name}, Age: #{stefani_age}, Occupation:
#{stefani_occupation}"

# => "Name: Stefani, Age: 49, Occupation: Firefighter"

Three variables per person is going to get really, really messy once we want to print 5, 10, or 100 business cards. We can clean this up quite a bit by considering that name, age, and occupation really just comprise a list of attributes about a person. We have a really great data structure for representing lists in Ruby...an array!

With that in mind, let's represent our data as an array:

bob     = ["Bob", 46, "Juggler"]
stefani = ["Stefani", 49, "Firefighter"]

If we wanted to print out Bob's name, we'd do it like this:

name = bob[0]

puts name

# => "Bob"

There's an extra step there, though! As we know, we can run whatever Ruby code we want inside the #{} in a string. So we can just access the first element in the array directly within the string:

puts "#{bob[0]}"

# => "Bob"

This is going to clean up our business card printer quite a bit!

bob     = ["Bob", 46, "Juggler"]
stefani = ["Stefani", 49, "Firefighter"]

puts "Name: #{bob[0]}, Age: #{bob[1]}, Occupation: #{bob[2]}"

# => "Name: Bob, Age: 46, Occupation: Juggler"

puts "Name: #{stefani[0]}, Age: #{stefani[1]}, Occupation: #{stefani[2]}"

# => "Name: Stefani, Age: 49, Occupation: Firefighter"

Nice! But even this is a bit much. The fact that we have to repeat so much code is a pretty good sign that we need a printer method.

So let's do that! Let's make a method, #print_business_card, that accepts an array representing a person, and then prints out their business card. First, we'll create the basic method signature:

def print_business_card(person)
end

Now, let's re-use the code we've already written to print out the passed-in person's details:

def print_business_card(person)
  puts "Name: #{person[0]}, Age: #{person[1]}, Occupation: #{person[2]}"
end

Something is missing, though. Our people need a phone number. Let's change our people arrays to look like this:

bob = ["Bob", 46, "Juggler", "555-555-5555"]

And in our #print_business_card method, let's print that out on a second line:

def print_business_card(person)
  puts "Name: #{person[0]}, Age: #{person[1]}, Occupation: #{person[2]}"
  puts "Contact: #{person[3]}"
end

Now, let's use this! Let's print out business cards for Bob and Stefani:

bob     = ["Bob", 46, "Juggler", "555-555-5555"]
stefani = ["Stefani", 49, "Firefighter", "555-111-1111"]

print_business_card(bob)

# => "Name: Bob, Age: 46, Occupation: Juggler"
# => "Contact: 555-555-5555"

print_business_card(stefani)

# => "Name: Stefani, Age: 49, Occupation: Firefighter"
# => "Contact: 555-111-1111"

String interpolation is basically a super power. And like any good super power, mastery comes with practice! (That's how Superman got so good at flying, right?) Your turn!

Instructions

  1. Define a method, #display_rainbow, in lib/display_rainbow.rb.
  2. #display_rainbow must accept an argument, an array of colors. The tests call #display_rainbow with the following invocation: display_rainbow(['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']).
  3. #display_rainbow should print out the colors of the rainbow in the following format: "R: red, O: orange, Y: yellow, G: green, B: blue, I: indigo, V: violet" by reading from the array passed in as an argument. (For this lab it is OK to hardcode the uppercase letters.)
  4. It should accept an array containing the colors as an argument.
  5. Run learn locally until you pass.
  6. Submit the lab.

colors will be passed in as: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

You must read from the colors argument and you should hardcode the order. Do not use #each or any loop. For example, given letters = ["b","a","c"] to print them in alphabetical order without iteration you should:

letters = ["b","a","c"]
puts "The first letter in the alphabet is: #{letters[1]}"
puts "The second letter in the alphabet is: #{letters[0]}"
puts "The third letter in the alphabet is: #{letters[2]}"

View Interpolation Super Power on Learn.co and start learning to code for free.

interpolation-super-power's People

Contributors

annjohn avatar aturkewi avatar aviflombaum avatar cjbrock avatar ga-be avatar loganhasson avatar maxwellbenton avatar peterbell avatar

Stargazers

 avatar

Watchers

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

interpolation-super-power's Issues

interpolation-super-power-cb-gh-000 doesn't have any Rspec files.

I am attempting to run the learn command, but this folder doesn't have any other files including Rspec files. I clicked Open on the Curriculum page, but there is only the lib folder inside with display_rainbow.rb

So I ended up with a message
You don't appear to be in a Learn lesson's directory. Please cd to an appropriate directory and try again.
When I try to send the learn command.

display_rainbow_spec.rb causing errors when passed empty array

When running #display_rainbow the rspec tests fail when passed an empty array, but there are no directions to either edit the tests or to deal with an empty array. Putting a default case in the method arguments still causes there to be an issue.

This could be fixed by modifiying the tests:
describe '#display_rainbow' do
it 'accepts one argument' do
allow(self).to receive(:puts)
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

expect { display_rainbow(colors) }.to_not raise_error(NoMethodError)
expect { display_rainbow(colors) }.to_not raise_error(ArgumentError)

end

it 'prints out the colors of the rainbow correctly when passed in in order' do
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

expect(colors).to receive(:[]).with(0).at_least(:once).and_return("red")
expect(colors).to receive(:[]).with(1).at_least(:once).and_return("orange")
expect(colors).to receive(:[]).with(2).at_least(:once).and_return("yellow")
expect(colors).to receive(:[]).with(3).at_least(:once).and_return("green")
expect(colors).to receive(:[]).with(4).at_least(:once).and_return("blue")
expect(colors).to receive(:[]).with(5).at_least(:once).and_return("indigo")
expect(colors).to receive(:[]).with(6).at_least(:once).and_return("violet")

expect { display_rainbow(colors) }.to output("R: red, O: orange, Y: yellow, G: green, B: blue, I: indigo, V: violet\n").to_stdout

end
end

OR

Alternatively, I did this in my code:
def display_rainbow(colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])
if not colors.any?
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
end
puts "#{colors[0][0].upcase}: #{colors[0]}, #{colors[1][0].upcase}: #{colors[1]}, #{colors[2][0].upcase}: #{colors[2]}, #{colors[3][0].upcase}: #{colors[3]}, #{colors[4][0].upcase}: #{colors[4]}, #{colors[5][0].upcase}: #{colors[5]}, #{colors[6][0].upcase}: #{colors[6]}"

end
display_rainbow(['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])

cloning is failing

Hi. When loading this lab cloning is failing all the time. Can this be somehow solved?

Error when output is correct?

def display_rainbow(colors)

  str = ""
  colors_and_first_letter = []

  colors.each{|i|
    first_letter = i[0,1].upcase
    colors_and_first_letter.insert(-1, "#{first_letter}: #{i}")
  }

  str = colors_and_first_letter.join(", ")
  puts"#{str}"

end

gets error

 Failure/Error: expect(colors).to receive(:[]).with(0).at_least(:once).and_return("red")
       (["red", "orange", "yellow", "green", "blue", "indigo", "violet"]).[](0)
           expected: at least 1 time with arguments: (0)
           received: 0 times
     # ./spec/display_rainbow_spec.rb:14:in `block (2 levels) in <top (required)>'
Finished in 0.0745 seconds (files took 0.32655 seconds to load)
2 examples, 1 failure
Failed examples:
rspec ./spec/display_rainbow_spec.rb:11 # #display_rainbow prints out the colors of the rainbow correctly when passed in in order

OAuth token a second time

Hi, I ran into this issue a few weeks ago, and it hasn't happened again until today. Can you tell me why it happens? Thanks.

courageous-program-2331@cdad0abbc98e:~$ learn open interpolation-super-power-v-000
chmod: cannot access '/home/courageous-program-2331/.netrc': No such file or directory
Connecting to Learn...
To connect with the Learn web application, you will need to configure
the Learn gem with an OAuth token. You can find yours at the bottom of your profile
page at: https://learn.co/your-github-username.

Once you have it, please come back here and paste it in: chmod: cannot access '/home/courageous-program-2331/.netrc': No such file or directory
^C/usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/cli.rb:27:in gets': Interrupt from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/cli.rb:27:in gets'
from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/cli.rb:27:in ask_for_oauth_token' from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/setup.rb:221:in setup_learn_config_machine'
from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/setup.rb:145:in setup_netrc' from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/setup.rb:38:in check_config'
from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/setup.rb:30:in run' from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/lib/learn_config/setup.rb:6:in run'
from /usr/local/rvm/gems/ruby-2.3.1/gems/learn-config-1.0.77/bin/learn-config:15:in <top (required)>' from /usr/local/rvm/gems/ruby-2.3.1/bin/learn-config:23:in load'
from /usr/local/rvm/gems/ruby-2.3.1/bin/learn-config:23:in `

'

confusing example: ROYGBIV

I found it confusing to automate something that would be easier just to puts. It would have made more sense to me if the little machine was doing something for me that reduced my own effort.

Correct Code Failed - Removing Default Argument Passed

The correct code pasted below did NOT work, and returned a failure: "spec ./spec/say_hello_spec.rb:10 # say_hello defaults to Ruby Programmer when no name is passed in..." (the rest was cut off from my 'Ask a Question').

def say_hello(name="Ruby Programmer")
puts "Hello #{name}!"
end

When I deleted the default argument, the code passed.
def say_hello(name)
puts "Hello #{name}!"
end
say_hello

Please fix the instructions, which require the inclusion of a default argument. I wasted valuable and unnecessary time trying to figure out how my correct code was wrong, which is VERY frustrating!! The "Ask a Question" rep was also very baffled as to how this happened.

print vs puts

This lab requires a nuanced knowledge of the difference between print and puts to pass, however, the curriculum is not very thorough at prepping for this. The clue that puts is the solution is \n added to the end of the error code, if one happens to fail by opting for print instead. This clue is searchable, the answer is obtainable, but why make it difficult and frustrating? Searching Google for what one doesn't know is sub-optimal knowledge acquisition. There's no reason why a student can't be completely found while performing a lab like this. I still fail to understand the implications of puts over print in this context, in a fluent, usable way, and that seems like a missed opportunity. If this depth of knowledge is not important yet, why allow one to fail over the other? For those who might opt to use print, the spotlight is immediately off of interpolation.

Wording could be better in instructions?

colors will be passed in as: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

display_rainbow should print out the colors of the rainbow in the following format: "R: red, O: orange, Y: yellow, G: green, B: blue, I: indigo, V: violet"

This section had me in a loop for hours. I was initially coding -
def display_rainbow (red = "R:red", orange = "O: orange" and so on)
and then trying to print it here individually.

It turned out the solution was to use the R: in the puts and just call the colour. I made this horrendously more difficult for myself because I think it's the first time we've been asked to "accept an array using the colours as an argument" - in that language. For a newbie like me. I found this lesson exceptionally confusing. It was the only lesson in the whole programme I've struggled with and had to spend a few hours on before biting the bullet and looking at the community solutions.

I think it's in the wording of the instructions. Just as your brain is doing little mental ticks on everything we've learned so far as you read down it, the "colors will be passed" section added on at the bottom seems like an after thought to throw you off.

Unclear Desired Outcome

Hey there,

I wanted to draw your attention to this lab. I was having a difficult time with the lab so I consulted one of the technical coaches.

After working with the technical coach, I found the error with my code, but the following code is what my technical coach suggested was correct:

`def display_rainbow(colors)
puts "R: #{colors[0]}, O: #{colors[1]}, Y: #{colors[2]}, G: #{colors[3]}, B: #{colors[4]}, I: #{colors[5]}, V: #{colors[6]}"
end`

While this code runs the "learn" function without error, it does not produce, what I believed to be the expected output of: "R: red, O: orange, Y: yellow, G: green, B: blue, I: indigo, V: violet".

With little issue I changed my code to run correctly, writing:

`colors = ["red", "orange", "yellow", "green", "blue", "indigo", "purple"]

def display_rainbow(colors)
puts "R: #{colors[0]}, O: #{colors[1]}, Y: #{colors[2]}, G: #{colors[3]}, B: #{colors[4]}, I: #{colors[5]}, V: # 
{colors[6]}"
end

display_rainbow(colors)`

I think this lab could benefit from being more direct about the desired code for the exercise--is it enough to post only the method, or is the desired outcome the output: "R: red, O: orange, Y: yellow, G: green, B: blue, I: indigo, V: violet"? If it is the latter, my technical coach was not on the same page, and when I continued to ask her why the array was not necessary for the lab, she failed to provide me with an answer I could understand as a beginner coder.

Learn.co not receiving completed lab

When I submit the assignment that has completed, and passed the test, the system is not receiving my final passed submission to continue to next lesson. How am I able to fix, so the lab is received by the system to show I've passed the lab?

Capture

Should the "R" in "R: red" be hardcoded or programmatically determined?

I have encountered a couple users who are able to correctly interpolate #{colors[0]} but are not sure how to programmatically get the first letter of the color and capitalize. For this lab, is the intention that they would achieve the programmatic or the hardcoded solution?

As a learn expert, which should we guide a user towards?

Here is an example question: https://learn.co/lessons/13394/?question_uid=q-45e3b450-a8d8-4463-9853-7502bf693121&batch_id=286&track_id=12307

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.