On Wed, May 16, 2012 at 4:25 PM, Matt Mencel <[email protected]> wrote:
> Hi,
>
> I'm not an OOP person. Most of the Ruby I write is just scripts and such.
> I've found a good place to start using real Class objects though and am
> having a hard time getting my head around it.
>
> I have this class. The @members attribute is an array of several 5 digit
> numbers (could be between 1 and 10 values in the array). I want to be able
> to find objects in the Class by using one of the numbers.
>
> class Crosslisting
> attr_accessor :members, :title, :id
>
> def initialize(members, name='', id='')
> @members = members
> @name = name
> @id = id
> end
>
> def self.find_by_member(member)
> found = nil
> ObjectSpace.each_object(Crosslisting) { |o|
> found = o if o.members.include?(member)
> }
> found
> end
> end
>
> members = ['12345','67890']
> my_obj = Crosslisting.new(members)
> ap Crosslisting.find_by_member('12345')
>
> # OUTPUT USING AWESOME_PRINT GEM
> #<Crosslisting:0x00e77410
> attr_accessor :id = "",
> attr_accessor :members = [
> [0] "12345",
> [1] "67890"
> ],
> attr_accessor :name = ""
>>
>
>
> This seems to work ok. Am I doing it right or is there a better way?
ObjectSpace is always a crutch. Better remember all elements
somewhere (e.g. in an instance variable of the class).
class Crosslisting
attr_accessor :members, :title, :id
def initialize(members, name='', id='')
@members = members
@name = name
@id = id
self.class.add(self)
end
def self.add(cl)
(@members ||= []) << cl
end
def self.find_by_member(member)
@members.find {|o| o.members.include?(member)} if @members
end
end
> I tried to figure out how to use 'def initialize(*args)' instead of naming
> all the attributes, but I'm not currently smart enough to make it work
> apparently.
Why would you want to do that? The code of #initialize is OK the way it is.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en