Programming Fundamentals - Lab 4 - Solution

The problem

From labs/4-hashes.rb in your copy of ruby-intro:

Start with an amount of Bitcoin that someone owns. Using the Ruby hash bitcoin_data, display a summary of Bitcoin data for the user. Something similar to the sample output.

Sample output:
1 Bitcoin is valued at $41405.1046 USD.
Your Bitcoin is worth $62107.6569.

Run it from the top folder of the repo (where README.md is):

bin/rails runner labs/4-hashes.rb

The code you don't change

The top of the file asks a live service for the current price of Bitcoin:

# DON'T CHANGE THIS CODE
# ----------------------
require "net/http"
require "json"
url = "https://blockchain.info/ticker"
uri = URI(url)
response = Net::HTTP.get(uri)
bitcoin_data = JSON.parse(response)
# ----------------------

We'll learn more about APIs later. For now: an API is how another piece of software shares its data with your code. A person would visit a website to see the price of Bitcoin; code asks the API instead. These lines go to that URL, get back text, turn the text into a Ruby hash, and save it in bitcoin_data. Everything after this is a hash, which you already know how to work with.

1 and 2. How much Bitcoin, as a number

The file starts you off:

bitcoin = "1.5"
bitcoin = bitcoin.to_f

The amount is in quotes on purpose. Anything a person types into a form or a terminal reaches your code as a string, even when it looks like a number. A string can't be multiplied, so .to_f turns it into a Float (a number with a decimal point). Change "1.5" to any amount you like.

3. Look at the hash before you dig into it

puts bitcoin_data

You'll see something like this (shortened, and your numbers will be today's):

{
  ...
  "EUR" => { "15m" => 74258.37, "last" => 74258.37, "buy" => 74258.37, "sell" => 74258.37, "symbol" => "EUR" },
  ...
  "USD" => { "15m" => 83165.11, "last" => 83165.11, "buy" => 83165.11, "sell" => 83165.11, "symbol" => "USD" }
}

It's a hash (the curly braces), with one key per currency. The value of each key is another hash. Look at just the one we want:

puts bitcoin_data["USD"]

There are a few prices in there. "last" is the most recent one, and it has no quotes around it, so it's already a number we can do math with.

4. Dig out the price, do the math, display it

usd_rate = bitcoin_data["USD"]["last"]
puts usd_rate

It never hurts to puts a value as a sanity check before you use it. Then the math:

usd_value = bitcoin * usd_rate

For the output, start with the sample text exactly as written, then swap the parts that should change for your variables:

puts "1 Bitcoin is valued at $41405.1046 USD."
puts "Your Bitcoin is worth $62107.6569."

becomes

puts "1 Bitcoin is valued at $#{usd_rate} USD."
puts "Your Bitcoin is worth $#{usd_value.round(2)}."

.round(2) keeps two decimal places, the way money is usually shown. Without it you may see a long tail of digits.

Final code

# 1. How much Bitcoin, as a string, the way typed input arrives
bitcoin = "1.5"

# 2. A string can't be multiplied: make it a Float
bitcoin = bitcoin.to_f

# 3. Inspect the hash: one key per currency, each a hash of its own
# puts bitcoin_data
# puts bitcoin_data["USD"]

# 4. Dig out the price, then do the math and display it
usd_rate = bitcoin_data["USD"]["last"]
usd_value = bitcoin * usd_rate

puts "1 Bitcoin is valued at $#{usd_rate} USD."
puts "Your Bitcoin is worth $#{usd_value.round(2)}."

Output (with today's price):

1 Bitcoin is valued at $83165.11 USD.
Your Bitcoin is worth $124747.67.

Challenge

Could you take this a step further? Add a variable for the currency, currency = "EUR", and show the price and the value in that currency instead. If the currency isn't one the API knows (try "XYZ"), show a message instead of an error.

A hint: when you ask a hash for a key it doesn't have, you get nil back.

currency = "EUR"
currency_data = bitcoin_data[currency]

if currency_data == nil
  puts "Sorry, #{currency} isn't a currency we have a price for."
else
  rate = currency_data["last"]
  value = bitcoin * rate
  puts "1 Bitcoin is valued at #{rate} #{currency}."
  puts "Your Bitcoin is worth #{value.round(2)} #{currency}."
end