Forum: Ruby on Rails Determine if a value is an instance of String , or Array , o

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
oo00oo (Guest)
on 2006-03-04 20:42
(Received via mailing list)
each loop inside a mixed hash
I need to determine if the value is an instance of String
How ?

hash.each do |k,v|
    if v ( instance of ) String
       hash[ k ] = v.capitalize
    enf
end
Rick T. (Guest)
on 2006-03-04 20:58
(Received via mailing list)
On 3/4/06, oo00oo <removed_email_address@domain.invalid> wrote:
>
> each loop inside a mixed hash
> I need to determine if the value is an instance of String
> How ?
>
> hash.each do |k,v|
>     if v ( instance of ) String
>        hash[ k ] = v.capitalize
>     enf
> end


Here's two different ways of doing it ... since I'm still pretty new to
ruby, I'm not sure if either of them is the best way (both use
capitalize!
rather to capitalize to change the value "in-place"):

hash.each do |k,v|
  v.capitalize! rescue v
end

OR

hash.each do |k,v|
  v.capitalize! if v.respond_to? :capitalize
end

Rick
Tore D. (Guest)
on 2006-03-04 21:10
hash.each{|k,v|
  v.capitalize! if v.is_a? String
}

Or use Rick's "duck typing" approach.


oo00oo wrote:
> each loop inside a mixed hash
> I need to determine if the value is an instance of String
> How ?
>
> hash.each do |k,v|
>     if v ( instance of ) String
>        hash[ k ] = v.capitalize
>     enf
> end
oo00oo (Guest)
on 2006-03-04 21:10
(Received via mailing list)
Thanks for the tips
inline rescue is nice !
But I'm always searching a method to determine a type. For Arrays,
Hashs...
Tore D. (Guest)
on 2006-03-04 21:16
object.is_a?(ClassName) does this.

object.class returns the class.

oo00oo wrote:
> Thanks for the tips
> inline rescue is nice !
> But I'm always searching a method to determine a type. For Arrays,
> Hashs...
Pete Y. (Guest)
on 2006-03-04 23:38
(Received via mailing list)
Also worth mentioning that you can do this:

   hash.each do |k, v|
     case v
       when String
         v.capitalize
       when Array
         # do something else
       else
         # do something else again
     end
   end

Pete Y.
http://9cays.com
Bob S. (Guest)
on 2006-03-05 02:26
(Received via mailing list)
hash = {'a' => 'bob', 'b' => 3, 'c' => 'fred' }

hash.each_value {|d| d.capitalize! if d.is_a?(String) }
=> {"a"=>"Bob", "b"=>3, "c"=>"Fred"}

So, to answer your question, use the is_a? (or kind_of?) method.


Bob S.
http://www.railtie.net/
This topic is locked and can not be replied to.