Â
Search
• Heather Marie

Code a Ruby Rainbow đđ¤

inÂˇterÂˇpoÂˇlaÂˇtion #ď¸âŁ

inËtÉrpÉËlÄSH(É)n/

noun

1. the insertion of something of a different nature into something else.

Letâs program a rainbow! đ đ¤

SoâŚ we need to talk to the machine by using the Ruby Programming Language. We have that already installed and setup and now we can open Mac Terminal and Xcode to get going.

But first, letâs ask ourselves some questions. We need step by step understanding on how to produce a coded rainbow.

• What colors are in the rainbow?

• In what format do we provide the color listing to the computer?

• What method do we need to tell the machine to process (think)? đ¤

• How can the color listing interpolate in to the machines method (thought process)?

• How can we tell the machine to show us what itâs thinking?

Letâs answer them in Xcode! đ đ¤

The colors are:

red, orange, yellow, green, blue, indigo, and violet

The color listing format is an array set to equal a variable of âcolorsâ:

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

The defined method has an argument of the variable âcolorsâ:

def display_rainbow(colors)

end

What we are doing is saying: hey computer, the colors are equal to these and what your thinking about and going to process for us is called method display_rainbow. But how can it take the colors and interpolate them into the method and print out our âcolorsâ?

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

Woah right? The hash (â#â) means to take the data from the âcolorsâ array and interpolate them into a hash. The numbers in a hash always begin with â0â.

Now we have our ruby code in Xcode:

Letâs Play! Letâs program a rainbow! đ đ¤

On a Mac, open terminal & type:

irb

Press Enter

Copy & Paste this code:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

Press Enter

Copy & Paste this code:

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

Press Enter

Now, Copy & Paste this code:

display_rainbow(colors)

Press Enter

The ruby rainbow: R: red, O: orange, Y: yellow, G: green, B: blue, I: indigo, V: violet

There are no colors showing up but the program believes itâs displaying a rainbow the same way you believe you see one. đ

ty

//âĽď¸