Created
November 18, 2010 21:58
-
-
Save thirtysixthspan/705724 to your computer and use it in GitHub Desktop.
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 'yaml' | |
class YAMLHash | |
def reload | |
raise 'File not found' if !File.exists?(@filename) | |
@data = YAML::load(File.open(@filename)) | |
end | |
def initialize(*filename) | |
if filename.size==1 | |
@filename = filename[0] | |
reload | |
else | |
@data = Hash.new | |
end | |
end | |
def save(filename) | |
@filename = filename if filename | |
File.open(@filename, 'w+') { |out| YAML::dump(@data, out) } | |
end | |
def method_missing(m, *args) | |
case args.size | |
when 0 | |
return @data[m.to_s] | |
when 1 | |
m = m.to_s.chop if m[-1]=='=' | |
@data[m] = args[0] | |
else | |
raise "Too many arguments provided to #{self.class}." | |
end | |
end | |
end | |
square=YAMLHash.new() | |
square.length = 5 | |
square.width = 5 | |
square.save('square.yaml') | |
puts "The area of the square is #{square.length * square.width}" | |
rectangle=YAMLHash.new('square.yaml') | |
rectangle.length = 10 | |
puts "The area of the rectangle is #{rectangle.length * rectangle.width}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment