Created
November 9, 2012 10:47
-
-
Save sivagao/4045109 to your computer and use it in GitHub Desktop.
using json @ ruby. from ruby best practices
This file contains hidden or 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 "json" | |
hash = { "Foo" => [Math::PI, 1, "kittens"], | |
"Bar" => [false, nil, true], "Baz" => { "X" => "Y" } } #... | |
puts hash.to_json #=> Outputs | |
{"Foo":[3.14159265358979,1,"kittens"],"Bar":[false,null,true],"Baz":{"X":"Y"}} | |
require "json" | |
json_string = '{"Foo":[3.14159265358979,1,"kittens"], ' + | |
'"Bar":[false,null,true],"Baz":{"X":"Y"}}' | |
hash = JSON.parse(json_string) | |
p hash["Bar"] #=> Outputs | |
[false,nil,true] | |
p hash["Baz"] #=> Outputs | |
{ "X"=>"Y" } | |
require "json" | |
require "open-uri" | |
require "cgi" | |
module GSearch | |
extend self | |
API_BASE_URI = | |
"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" | |
def show_results(query) | |
results = response_data(query) | |
results["responseData"]["results"].each do |match| | |
puts CGI.unescapeHTML(match["titleNoFormatting"]) + ":\n " + match["url"] | |
end | |
end | |
def response_data(query) | |
data = open(API_BASE_URI + URI.escape(query), | |
"Referer" => "http://rubybestpractices.com").read | |
JSON.parse(data) | |
end | |
end | |
require "json" | |
class Point | |
def initialize(x,y) | |
@x, @y = x, y | |
end | |
def distance_to(point) | |
Math.hypot(point.x - x, point.y - y) | |
end | |
attr_reader :x, :y | |
def to_json(*args) | |
{ 'json_class' => self.class.name, | |
'data' => [@x, @y] }.to_json(*args) | |
end | |
def self.json_create(obj) | |
new(*obj['data']) | |
end | |
end | |
point_a = Point.new(1,2) | |
puts point_a.to_json #=> {"json_class":"Point","data":[1,2]} | |
point_b = JSON.parse('{"json_class":"Point","data":[4,6]}') | |
puts point_b.distance_to(point_a) #=> 5.0 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment