From: "Mauricio Fernández" Date: 2003-09-13T21:11:46+09:00 Subject: Re: Duck Typing On Sat, Sep 13, 2003 at 07:53:18PM +0900, Meino Christian Cramer wrote: > Another code snippet I did in irb gaves me headaches also. Here it > is: > > >> a=Array.new // a shiny new array, full of ducks ;) > => [] > >> a=[[1,2],3] // fill in some extra ducks > => [[1, 2], 3] > >> a.respond_to?(:[]) // check whether we have an array > => true // expected... > >> a[0].respond_to?(:[]) // check wether first entry itself is > // an array > => true // ok, expected, too > >> a[1].respond_to?(:[]) // now the "pure " 3...is it an array, too ? > => true // OH! SURPRISE! It is an array...! (?) > >> b=a[1] // lets put it in a clean variable > => 3 > >> b.respond_to?(:[]) // now... > => true // Again ... it seems to array-able What you see is Fixnum#[] -------------------------------------------------------------- Fixnum#[] fix[ n ] -> 0, 1 ------------------------------------------------------------------------ Bit Reference---Returns the nth bit in the binary representation of fix, where fix[0] is the least significant bit. a = 0b11001100101010 30.downto(0) do |n| print a[n] end produces: 0000000000000000011001100101010 > What do I wrong here??? > > Background is the following: > > I have either an hash of the following pattern > > a=Hash.new > > a=["", ["","filename]] I guess this is only your notation and not the code you're feeding to ruby :) > OR of that pattern: > > a=["", [["","filename],["","filename],....]] > > To print both versions, I have handle the value of the hash differently. > > Currently my method tries to figure out, how to print, with the > help of "respond_to?". > > And it fails due to the above things I did in irb. That's because String has an instance method named [], too. You'd have to use is_a? Array, but I'd rather change the code so that in the first pattern you have an array of length 1. ie bla["0xff"] = [["bla", "file.rb"]] bla["0x01"] = [["foo", "file2.rb], ["bar", "file3.rb"]] This way the same code can work for both cases. -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com ...and scantily clad females, of course. Who cares if it's below zero outside. -- Linus Torvalds