I would like to use a string as an attribute (of a class)
example:
o=Someclass.new
attr='name'
then if executing
puts o.attr
gives the error: ...attr is not a method...
any help appreciated
Erik
| SitePoint Sponsor |
I would like to use a string as an attribute (of a class)
example:
o=Someclass.new
attr='name'
then if executing
puts o.attr
gives the error: ...attr is not a method...
any help appreciated
Erik
Your someClass could look like this:
The attr_accessor call creates a getter and a setter method for you, so you can access the attribute @attr, which is private.Code:class Someclass attr_accessor :attr def initialize(attr) @attr = attr end end
If your only OO language is JavaScript, then you will need to spend a few hours learning how Ruby's classes and methods work. The may look similar if you squint and look at them sideways, but they are conceptually very different.
Oh, I got it now, sorry for the misunderstanding. Yes, in fact you can do that too, and in one line. Just call the send method:
You can include arguments after the method name, too:Code:puts o.send(attr)
Code:o.send('name=','Bob')


or, in this case:
Code:o.send(attr + '=','Bob') # or o.send("#{attr}=", 'Bob')
If you give someone a program,
you will frustrate them for a day;
if you teach them how to program,
you will frustrate them for a lifetime.
Ended up with:
o.send(ATTRS[index] + '=',item)
------------------------------------
ATTRS is an array of instance attributes which exist in Someclass.
Value of item comes from a text file with lines of values, like:
"ssa","asa","sdsd","sdsd","sdsd"
"svsa","asbcxvba","sxcvbdsd","svbndsd","scvndsd"
"snsa","acsa","sdnmsd","sdnmsd","snbmdsd"
.
.
.
Thanks for the help
Erik
Bookmarks