Bitcoin price with Ruby

codesharedot

codesharedot

Posted on October 24, 2019

Bitcoin price with Ruby

We aren't talking about the value of a Ruby or a get rich quick talk. No, we are talking about the programming language Ruby.

Getting the bitcoin price is one the simpelest program you can make, while still having a meaning (beyond "Hello World")

How can we do that with Ruby?

Get price with Ruby

The first step is to import some modules, or as ruby calls them gems.

#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
require 'open-uri'

Data is retreived from an API. We use an API to download data. In this example we download the bitcoin price.

Data is presetend to the computer in some way. Sometimes its XML Format, sometimes JSON, sometimes something else.

I like the JSON format personally, because it's so simple.

obj = JSON.load(open("https://api.coinmarketcap.com/v1/ticker/bitcoin/"))

Then it returns the JSON data, something like this

[{"id"=>"bitcoin",
  "name"=>"Bitcoin",
  "symbol"=>"BTC",
  "rank"=>"1",
  "price_usd"=>"7511.40312364",
  "price_btc"=>"1.0",
  "24h_volume_usd"=>"16880618621.5",
  "market_cap_usd"=>"135289661862",
  "available_supply"=>"18011237.0",
  "total_supply"=>"18011237.0",
  "max_supply"=>"21000000.0",
  "percent_change_1h"=>"0.05",
  "percent_change_24h"=>"-0.26",
  "percent_change_7d"=>"-7.3",
  "last_updated"=>"1571949454"}]

So we need to get the price (prie_usd). The price has micro cents, mili cents, nano cents and so on. This has no real world meaning, so we round the number after converting it to a floating point number..

val = obj[0]["price_usd"].to_f.round(2)
puts "$ #{val}"

Thats it

Related links

💖 💪 🙅 🚩
codesharedot
codesharedot

Posted on October 24, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related