Skip to content

Instantly share code, notes, and snippets.

@kangkyu
Forked from jendiamond/challenge.md
Created October 1, 2015 03:28
Show Gist options
  • Save kangkyu/dc65c39eb6a0e24d0a1b to your computer and use it in GitHub Desktop.
Save kangkyu/dc65c39eb6a0e24d0a1b to your computer and use it in GitHub Desktop.
Convert this string

string = "{key:[[value_1, value_2],[value_3, value4]], 5:10:00AM]}"

to this hash:

h = {"key" => [["value_1", "value_2"],["value_3", "value4"]], 5=>"10:00AM"}

then convert h to JSON.

Please note that the brackets are unbalanced on purpose.

===

require 'json'

string = "{key:[[value_1, value_2],[value_3, value4]], 5:10:00AM]}"
string.slice!(-2)
string = string.insert(-2, "'").insert(-10, "'").slice!(-11) && string.insert(-11 , "=>").slice!(4) && string.insert(4 , "=>")
string = string.insert(1, "'").insert(5, "'").insert(10, "'").insert(18, "'").insert(21, "'").insert(29, "'").insert(33, "'").insert(41, "'").insert(44, "'").insert(51, "'")

p string =  eval(string).to_json

Write a class Sample whose initialize method takes an arbitrary hash, e.g.

h = {"this" => [1,2,3,4,5,6], "that" => ['here', 'there', 'everywhere'], :other => 'here'}

Represent each key in the hash as an attribute of an instance of the class, such that I can say:

c = Sample.new(h)
c.this should return [1,2,3,4,5,6]
c.that  should return ['here', 'there', 'everywhere']
c.other should return 'here'

===

class Sample

    h = {"this" => [1,2,3,4,5,6],
         "that" => ['here', 'there', 'everywhere'],
         :other => 'here'}
def initialize(h)
    @h = h
    @h.each do |key, value|
      self.class.send(:attr_accessor, key)
        self.send("#{key}=", value)
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment