From: Joseph McDonald Date: 2001-05-15T11:21:46+09:00 Subject: [ruby-talk:15135] specifying argument type to method? Hi, I'd like to specify that a method accepts it's argument as a specified type. How can I do this? Here is the problem: I want to pass in name-based arguments to the method fetch(), sometimes I need to send in 2 arguments that have the same name, i.e: fetch('create_time' => ['<', 112341234],'create_time' => ['>', 112111234], 'other' => 'a') It doesn't help to do things like: def fetch(args=[]) or: def fetch(*args) The first one reads in the args as a hash unless you don't pass any, in which case you get an empty array. The second one simply assigns the keyword hash as the first element of the args array. So, I can't think of a way to pass multiple values for the same keyword without making the keyword value an array, like: fetch('create_time' => [ ['<', 123412341], ['>', 111121234] ]) But that is not very readable. :( So, how to "cast" the type that fetch gets? If that was possible, I could make it some homegrown type that is a hash, but converts the values to arrays if more than 1 instance of a key is detected. Also, I ran into something weird when investigating this: I thought this would work, but it didn't. Also, Of course I wouldn't reccomend changing Hash... just wanted to see if it would work. The idea is if we could associate this type of hash with the args to fetch... Weird thing is that it didn't work, and I don't know why. It almost seems like there are 2 versions of Hash running around in the program. # an array hash... if a key already exists, make it's value an array. class Hash alias oldset []= def []=(k,v) if self[k] arr = [] arr << self[k] << v oldset k, arr else oldset k, v end end end def fetch(args) p args p args.type end fetch("create_time" => ['<', 112341234], "create_time" => ['>', 112111235], "other" => "joe") m = Hash.new m["joe"] = 123 p m m["joe"] = 456 p m m["tom"] = 890 p m Output: {"create_time"=>[">", 112111235], "other"=>"joe"} Hash {"joe"=>123} {"joe"=>[123, 456]} {"joe"=>[123, 456], "tom"=>890} weird huh? thanks, -joe