tags:

views:

42

answers:

2

Say I have a class with many attributes but need only one attribute at a time, i.e.

   class A
     attr_accessor :name
     attr_accessor :other1
     attr_accessor :other2
     attr_accessor :other3
     attr_accessor :other4
   end

And want the output of only one attribute at a time:

   a = A.new
   puts a.name.to_str

to be:

  name value of a: value_of_name

What is the best way of doing this?

A: 

In the A class create a to_s method. This should override the default one.

e.g.

class A
def initialize
end

def to_s
puts "Name for a: #{name}"
end

end
aaronmase
I want to call to_str on the attribute name, not on the object a. is this possible?
poseid
Probably best to create your own method in this case that displays the name in your preferred format?
aaronmase
you mean, there is no other way than defining a class Name with custom to_str and include this into A ?
poseid
Name is pointing to a string object, the string object belongs to a string class with a to_str (or to_s) method- you could override the method here but it is not wise!
aaronmase
"Appreciation is more rewarding than any financial reward."
aaronmase
A: 

Edit:

You wouldn't consider just creating a method in the class that does this for you?

def as_string(sym)
  "value of #{sym.to_s}: #{send(sym)}"
end

Then you could use a.as_string(:attributename) to get the result you want? Otherwise you're looking for an attribute to act as an object, and doing attr_accessors aren't really the way to go..

Old Answer:

You need to override the to_s method in the class definition. Note that this is implicitly called by puts - when a method expects a string, it will automatically attempt to_s, so you don't need to.

Jeriko
thanks. I see attr_accessors usage is limited for my purpose indeed
poseid
"Appreciation is more rewarding than any financial reward."
aaronmase