From: Dylan Evans Date: 2009-03-19T11:23:41+09:00 Subject: Re: Is this how you start a hash? --0016e64f80b497955f04656f86b0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit On Thu, Mar 19, 2009 at 10:50 AM, Power One wrote: > I'm looking at the code below but still not clear about how this hash > forms! The author of a ruby book I read claimed that the code forms > hash. Is it? > > #not complete code, if you try to use it, it won't work! > > require 'yaml' > require 'wordplay' > > class Bot > attr_reader :name > > def initialize(options) > @name = options[:name] || "Unnamed Bot" > begin > @data = YAML.load(File.read(options[:data_file])) > rescue > raise "Can't load bot data" > end > end > end Not sure what the author was getting at but YAML#load will probably return a hash from the data file. The usage of options implies that a hash is passed as an argument > > > So, when you created hash, don't you have to initialize it with an empty > hash? For example: @name = {}? @name looks like it's supposed to be a string which is initialized from the options hash, the || notation means that if options[:name] doesn't exist then it will default to "Unnamed Bot". > > > Also when I try to use a snippet in irb: > @name = options[:name] || "Unnamed Bot" > NameError: undefined local variable or method `options' for main:Object > from (irb):1 > from :0 You will need to initialize the hash in this case, or use variables, but it might be best if your using irb to use constants such as; @name = "Robocop" > > > options is also in File.read(), it's acting like adding more element to > a hash. Am I right? Though irb tells a different story as if it's not > how you starting a hash. No it's not adding elements to the options hash, it is reading them. That line returns a hash to @data (which is probably the one you want) based on the contents of the file referred to by options[:data_file]. > > > I'm confused! Aren't we all? > > -- > Posted via http://www.ruby-forum.com/. > > -- The UNIX system has a command, nice ... in order to be nice to the other users. Nobody ever uses it." - Andrew S. Tanenbaum --0016e64f80b497955f04656f86b0--