[#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:04239] Re: @ variables not updated within method?

From: Hugh Sasse Staff Elec Eng <hgs@...>
Date: 2000-07-27 18:01:24 UTC
List: ruby-talk #4239
On 27 Jul 2000, Dave Thomas wrote:

> 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.

Aha, that it why I am getting them all the same!
> 
>   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

OK, I'll be a bit more careful about that.

> by writing something like:
> 
>   fred = {}
> 
>   fred['hugh'] ||= []           # create entry if none there
> 

Hmm, that is cunning.  :-) 

>   fred['hugh'][0] = 'hello'
> 
>   fred                          # {"hugh"=>["hello"]}
> 
> 
> Did this make sense? I'm on the wrong side of the sleep curve at the
> moment ;-)

It was spot on. thank you.
> 
> 
> Dave
> 
> 
	Hugh
	hgs@dmu.ac.uk



In This Thread