converting object into array

S

Suresh Napster

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',..]
 
B

Brian Candler

Suresh said:
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.
 
F

Fabian Streitel

[Note: parts of this message were removed to make it a legal post.]

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

2009/10/14 Suresh Napster said:
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!
 
P

Paul Smith

hi guys,


=A0i 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....


=A0['john','12','male',..]

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



--=20
Paul Smith
http://www.nomadicfun.co.uk

(e-mail address removed)
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

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

Curious: why that construct instead of:

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,166
Messages
2,570,907
Members
47,446
Latest member
Pycoder

Latest Threads

Top