DEV Community

Cover image for Bitcoin price with Ruby
codesharedot
codesharedot

Posted on

1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay