[Ruby] string.to_primitive and string.to_collection

Michael Judge mjudge at surveycomplete.com
Wed Oct 4 10:26:02 PDT 2006


> class String
>    def to_primitive
>      Integer(self) rescue Float(self) rescue ... rescue self
>    end
> end
>   
> class String
>    def to_hash
>      Hash[*self.scan(/(\S+)[:.]\s+(.+)/).flatten ]
>    end
> end
Nice improvements.  I appreciate the input.  Using rescue without a 
begin wrapper is new to me.
> Please don't hijack threads. Start a new mail.
Sounds like a good idea.

- Michael Judge

Ryan Davis wrote:
> 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+[:.]\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.
>
> _______________________________________________
> Ruby at zenspider.com
> http://www.zenspider.com/seattle.rb
> http://www.zenspider.com/mailman/listinfo/ruby
>
>
>
>   



More information about the Ruby mailing list