From: "trans. (T. Onoma)" Date: 2004-09-22T03:58:08+09:00 Subject: Re: Array#index block and rdetect On Tuesday 21 September 2004 10:28 am, Yukihiro Matsumoto wrote: > Hi, > > In message "Re: Array#index block and rdetect" > > on Tue, 21 Sep 2004 20:33:52 +0900, "trans. (T. Onoma)" writes: > |For sake of interchangeability (after all that's the upside of ducktyping) > |have an alias for both: > > Arrays have number index, and hashes have arbitrary type of keys, so > that there should hardly be the case of need for interchangeability > between them. Do you have any example of the usage? Well, like anything of this sort one doesn't have examples off hand b/c this can't be done currently --one ends up doing them other ways. Same goes for ordered hashes. I've run into a need for them many times, but find alternate solutions b/c they are not available. So I have no ready use cases of them either, but I know they can be useful. Just the same I put together a simple example to give a taste. It shows how one general method might do the job, rather then having special cases. It is given below. > Currently, I'd rather feel that it's good to avoid the term "index" > for hashes, for example, renaming IndexError to KeyError for Hash > class. I go both ways. I think interchangeable parts are good --it goes along with the ideas of duck types. But sometimes it is also good for things to be different. In this case it might be better b/c if hashes ever get order, then index will be needed for that, not key. So yes on this I agree with you but only if order will eventually be usable for hashes. Otherwise interchangeable is more useful. # SIMPLE DEMO play_list = [ 'i never was cool', 'SEA CHANGE', 'Shepherd Moons' ] artists = { 'i never was cool' => 'anna wolfe', 'SEA CHANGE' => 'Beck', 'Shepherd Moons' => 'Enya' } def show(x) x.each_with_index{|v,i| puts "#{i} => #{v.upcase}" } end #=begin # remove first '#' to deactivate section # Not Interchangeable puts "\nMy Play List" show(play_list) puts "\nArtist Reference" show(artists) puts "\nArtists In Order of Play" show(play_list.collect {|n| artists[n] }) puts =begin in `show': undefined method `upcase' for ["Shepherd Moons", "Enya"]:Array (NoMethodError) =end # Interchangable class Hash def each_with_index each_pair{|k,v| yield(v,k)} end end puts "\nMy Play List" show(play_list) puts "\nArtist Reference" show(artists) puts "\nArtists In Order of Play" show(play_list.collect {|n| artists[n] }) puts =begin My Play List 0 => I NEVER WAS COOL 1 => SEA CHANGE 2 => SHEPHERD MOONS Artist Reference Shepherd Moons => ENYA SEA CHANGE => BECK i never was cool => ANNA WOLFE Artists In Order of Play 0 => ANNA WOLFE 1 => BECK 2 => ENYA =end -- ( o _ カラチ // trans. / \ transami@runbox.com I don't give a damn for a man that can only spell a word one way. -Mark Twain