[#3986] Re: Principle of least effort -- another Ruby virtue. — Andrew Hunt <andy@...>

> Principle of Least Effort.

14 messages 2000/07/14

[#4043] What are you using Ruby for? — Dave Thomas <Dave@...>

16 messages 2000/07/16

[#4139] Facilitating Ruby self-propagation with the rig-it autopolymorph application. — Conrad Schneiker <schneik@...>

Hi,

11 messages 2000/07/20

[ruby-talk:04236] Re: @ variables not updated within method?

From: Dave Thomas <Dave@...>
Date: 2000-07-27 17:52:31 UTC
List: ruby-talk #4236
Hugh Sasse Staff Elec Eng <hgs@dmu.ac.uk> writes:

> I have a program, too large to post here, and an object in it with a
> variable:
> 
> @chunks = Hash.new([])

What this does is to set the default value for any unknown keys at an
empty array. It will be the same array for any missing key.

  fred = Hash.new([])		# => {}
  fred['dave']		        # => []
  fred['hugh']	          	# => []
  fred['dave'][0] = 'hello'	# => "hello"
  fred['hugh']                  # => ["hello"]   !!!


But - having done this, I still haven't actually created any members
in the hash-all I've done is access the default value:

  fred.inspect                  # => "{}"

Unlike Perl, Ruby doesn't automagically create the sub-arrays the
first time you reference one. You could do it by subclassing Hash, or
by writing something like:

  fred = {}

  fred['hugh'] ||= []           # create entry if none there

  fred['hugh'][0] = 'hello'

  fred                          # {"hugh"=>["hello"]}


Did this make sense? I'm on the wrong side of the sleep curve at the
moment ;-)


Dave

In This Thread