Ruby で 為替レート を取得(SGD/JPY)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'open-uri' | |
require 'json' | |
BASE_URI = "https://openexchangerates.org/api/" | |
API = "latest.json" | |
## APP_ID は API key のようなものです。openexchangerates.org 登録すると発行されます。 | |
APP_ID = "YOUR_APP_ID" | |
uri = BASE_URI + API + "?app_id=" + APP_ID | |
## API にアクセスします。JSON が返されます。ほんとは例外処理とか必要です。 | |
## API 詳細については下記ドキュメントを参照してください。 | |
## https://openexchangerates.org/documentation | |
response = open(uri) | |
## HTTPレスポンスのステータスコードを取得します、 | |
response_code = response.status[0] | |
## ステータスコードが 200 OK | |
if response_code == '200' | |
## JSON のパース結果を取得します。 | |
result = JSON.parse(response.read) | |
timestamp = result['timestamp'] | |
rates = result['rates'] | |
usd_jpy = rates['JPY'] ## USD/JPY を取得します。 | |
usd_sgd = rates['SGD'] ## USD/SGD を取得します。 | |
sgd_jpy = usd_jpy * (1/usd_sgd) ## SGD/JPY を計算します。 | |
puts "timestamp \t #{Time.at(timestamp)}" | |
puts "SGD/JPY \t #{sgd_jpy}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment