hey there,
looks like the first time around we didn’t manage to answer your
question
i’ll give it another shot…
i see three easy ways of doing what you want to do, though there well
may be others.
first, you can create an instance of the Sample class from within the
WebClient class, and then call the #atom method on that instance. that
might look something like this:
class NotAWebClient
def initialize
types = [“data1”, “data2”]
types.each{|type| some(type)}
end
def some(type)
case type
when “data1”
puts “got type data1, staying in NotAWebClient class.”
when “data2”
puts “got type data2, calling method from Sample class…”
#### here's the bit that will change....
s = Sample.new # create an instance of the Sample class
s.atom # call the atom method on that instance
end
end
end
class Sample
def atom #### this bit will also change
puts “…now in Sample class, atom method.”
end
end
test = NotAWebClient.new
see how that worked? in this case we created the atom method as an
instance method, which can be called upon - you guessed it - instances
of a class.
next, we’ll do it without creating an instance of the Sample class.
to do this, we’ll create a class method called ‘atom,’ rather than an
instance method. i’ve tried to make the places the changes go as
obvious as possible… so, in the Sample class, instead of writing…
def atom
puts “…now in Sample class, atom method.”
end
…write
def self.atom
puts “…now in Sample class, atom method.”
end
the keyword ‘self’ makes this a class method, which is called
directly, without needing to create an instance of the class.
now, back in the WebClient class, you’ve got to change how the method
is called. replace these two lines:
s = Sample.new # create an instance of the Sample class
s.atom # call the atom method on that instance
… with this one:
Sample.atom # no need to create an instance, call the method directly
… and run the program again - see that? same results, different
ways of getting there. the way you choose depends on whether you need
or want an instance of the Sample class hanging around. if you don’t
you might consider the third way i see of doing this, which would be
creating ‘Sample’ as a module, rather than a class - but that’s a topic
for another day!
hth -
good luck -