Converting object into array

hi guys,

i am newbie to ruby and i have an object like @user.And i have values
like inside that object name,age,sex,etc…I want to output like
this…

[‘john’,‘12’,‘male’,…]

Suresh N. wrote:

i am newbie to ruby and i have an object like @user.And i have values
like inside that object name,age,sex,etc…I want to output like
this…

[‘john’,‘12’,‘male’,…]

Show the code you have so far, and what extra functionality you would
like
(e.g. “puts @user” to output the string above; or @user.to_a to return
an array in the format above). Then we can show you how to extend your
code to do what you want.

Preferably, post this in the form of a small self-contained program
which actually runs. Then we can modify it, test it, and post the
updated version.

Regards,

Brian.

There are several questions that come to my mind before answering
your question is possible:

2009/10/14 Suresh N. [email protected]

And i have values
like inside that object name,age,sex,etc…I want to output like
this…

[‘john’,‘12’,‘male’,…]

How do you have those “inside that object”?
How can you access them?
What kind of Object is @user?

Some kind of example code would help us get a
clearer view of your problem.

e.g. if @user is of a custom class User with
attr_accessors for :name, :age etc.
then you could do something like this:

puts [@user.name, @user.age, @user.sex]

Greetz!

On Wed, Oct 14, 2009 at 12:44 PM, Suresh N. [email protected]
wrote:

hi guys,

i am newbie to ruby and i have an object like @user.And i have values
like inside that object name,age,sex,etc…I want to output like
this…

[‘john’,‘12’,‘male’,…]

class User
def to_array
[] << @name << @age << @sex
end
end


Posted via http://www.ruby-forum.com/.


Paul S.
http://www.nomadicfun.co.uk

[email protected]

At 2009-10-14 07:52AM, “Paul S.” wrote:

class User
def to_array
[] << @name << @age << @sex
end
end

Curious: why that construct instead of:

 def to_array
   [@name, @age, @sex]
 end

?

On Wed, Oct 14, 2009 at 2:55 PM, Glenn J. [email protected] wrote:

def to_array
  [@name, @age, @sex]
end

No reason. Just the first way it came into my head. I like yours
better.


Paul S.
http://www.nomadicfun.co.uk

[email protected]

On Wed, Oct 14, 2009 at 9:14 AM, Paul S. [email protected]
wrote:

def to_array
  [@name, @age, @sex]
end

Probably go with to_a to follow conventions used by other code ie
(1…5).to_a

Original question isn’t very clear, it sounds like OP might be wanting
the
brackets to be output as well, in which case you could use the inspect
method on the array

puts @user. http://user.name/to_a.inspect

This is the same as

p @user. http://user.name/to_a

[‘john’,‘12’,‘male’,…]

If you want the output to LITERALLY display like this…

@user.inspect

Regards,

  • Mac

Paul S. wrote:

class User
def to_array
[] << @name << @age << @sex

A literal Array would be prettier IMHO:

[@name, @age, @sex]

end
end