[Ruby] string.to_primitive and string.to_collection

Ryan Davis ryand-ruby at zenspider.com
Tue Oct 3 19:50:31 PDT 2006


On Oct 3, 2006, at 5:49 PM, Michael Judge wrote:

> Snippet 1: Convert a string to its most appropriate primitive type
> (i.e., string, integer or float.)

Pretty cool. I hadn't thought of doing something like that.

> Examples:
>
>   "12".to_primitive #=> 12
>   "13.8".to_primitive #=> 13.8
>   "abc".to_primitive #=> "abc"
>
> Code:

Try this easier-to-read version:

class String
   def to_primitive
     Integer(self) rescue Float(self) rescue ... rescue self
   end
end

> -----
>
> Snippet 2.  Convert a multi-line string into its most appropriate
> collection type (i.e., array or hash.)   For hashes, each line should
> fit the format: key. value or key: value.  (The key should be one  
> word.)
>
> How is this useful?  Well, you can fake a here-doc constructor for
> hashes and arrays.

I question the utility of this type of tool. It does too much and  
returns too many different types of things based on... well, it seems  
arbitrary. Split is sufficient for arrays. A simple hash-only version  
could be written as:

class String
   def to_hash
     Hash[*self.scan(/(.+)[:.]\s+(.+)/)).flatten]
   end
end

That said, it looks like you're doing some cool stuff. I'm not really  
sure what you mean by scary escaping stuff wrt YAML.



More information about the Ruby mailing list