[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

short cut to do a inspect method for object

junkone

7/23/2006 9:56:00 PM

I have a object with following instance variables
def initialize(symb)
#puts symb
@symbol=symb

@name=@exchange=@news=@summary=@sector=@industry=@category=@markedBad=""
end

Is there a quick way to override the inpect method to return the
instance variable name and values in a array?

1 Answer

Michael Fellinger

7/24/2006 3:12:00 AM

0

On Monday 24 July 2006 07:00, junkone@rogers.com wrote:
> I have a object with following instance variables
> def initialize(symb)
> #puts symb
> @symbol=symb
>
> @name=@exchange=@news=@summary=@sector=@industry=@category=@markedBad=""
> end
>
> Is there a quick way to override the inpect method to return the
> instance variable name and values in a array?

class A
  def initialize
    @a=:aa
    @b=:bb
    @c=:cc
  end
end
A.new.inspect
# "#<A:0xb7c197a4 @c=:cc, @a=:aa, @b=:bb>"


class A
  def inspect
    instance_variables.map{ |iv| [ iv, eval(iv).inspect ] }
    # yes, i'm ev(a|i)l here... use instance_variable_get instead - it's just
    # too long for this line :|
  end
end

A.new.inspect
# [["@c", :cc], ["@a", :aa], ["@b", :bb]]


class A
  def inspect
    instance_variables.map do |iv|
      "#{iv}=#{instance_variable_get(iv).inspect}"
    end .join(', ')
  end
end

A.new.inspect
# "@c=:cc, @a=:aa, @b=:bb"