class - Creating classes for geometric shapes (points, lines, square, triangle, etc) (ruby) -


i'm studying in code-school right , mentor give home work, don't it. can me?

so, asked create geometric shapes via classes:

  1. first of must create class point
  2. then must create class line (line - when 2 points connected)
  3. and next step, example want create square

and i've started code, , created class point, accessible coordinates (2d):

class point   attr_accessor :x, :y   def initialize     @x = 10     @y = 10   end   def x=(value)     @x = value   end   def x()     @x   end   def y=(value)     @y = value   end   def y()     @y   end end 

and example want create new point class. so:

p = point.new   p.x = 1   p.y = 5   print p # -> #<point:0x007f9463089cc0> 

and result have thing this:

#<point:0x007f9463089cc0> 

what mean?

but if ask print p.x , p.y - have understandable result:

print p.x, ", ", p.y # -> 1, 5 

am doing wrong or how can understand result on screen?

please, need understand this...

thanks help!

and question appears, there use in real programming job create point, lines , geometric shapes?

first of don't need setters , getters. mean don't need write these methods:

  def x=(value)     @x = value   end   def x()     @x   end   def y=(value)     @y = value   end   def y()     @y   end 

the reason why don't need methods because have call:

attr_accessor :x, :y 

and method (attr_accessor) job you.

second, might want allow flexibility in constructor, i.e., initialize method allow passing values x , y , default them 10 if nothing passed. can this

def initialize(x = 10, y = 10)   @x = x   @y = y end 

this way, this:

p1 = point.new  puts p.x # => 10 puts p.y # => 10  p2 = point.new(15, 20) puts p.x # => 15 puts p.y # => 20 

notice how p1 don't pass arguments , yet x , y both set expected, that's because setting default value them in method definition, here:

def initialize(x = 10, y = 10) 

now, regarding question why see this:

p = point.new p.x = 1 p.y = 5 print p # -> #<point:0x007f9463089cc0> 

what point:0x007fa003885bf8 means have instance of class point (which have in variable p). default ruby call to_s method on object when try print it, since in case didn't define method go through inheritance chain see defines method. turns out that method found in object class (all ruby objects implicitly inherit object class) , method's default behaviour print name of class followed instance's id in memory, in format: # (check: http://ruby-doc.org/core-2.3.1/object.html#method-i-to_s)

if want change can override to_s method this:

def to_s   "point #{x},#{y}" end 

that way get:

puts point.new # => point 10,10 

hope helps.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo