How can I overwrite a class variable? What I have here is a class
called Machine which calculates how many times a rectngle fits in a 60 x
120 rectangular shape and its working, in the code below it could fit 36
times, the problems is that I’m going to have differnet methods which
are supose to overwrite @@kerf and make the calculation based on these
new values but I do not know how to overwrite the class variable @@kerf.
How can I overwrite variable @@kerf so that when I call method "laser
(machine1.laser) the result would be 6 instead of 36 and when the method
“rurret” (machine1.turret) is called the result would be 12 instead of
36?
To be honest you do not need class variables for this and you should
not do the calculation in the initialize method as you do not know
what value to use for kerf. This is a better solution.
class Machine
def initialize(part_width, part_length) @part_width = part_width @part_length = part_length
end
This makes me feel good and bad, good because its increible to see
people helping others and whats best see people that identify the
problem in a metter of seconds (you guys are awesome) and bad becuase I
could’t figure this out by my self
Ideally, write small classes that solve a given problem,
then re-use those classes to make a larger project.
Do you know of any tutorials where you can actually practice Ruby in
actual projects? Not tutorials on the Ruby syntax (projects using Ruby)
I have another question, in Peters code he used “private” but if I
remove it, it actually works can someone explain the use of private
here, is this the way of making a private def in Ruby? Meaning that this
def will not be accessible outside the class.
I have another question, in Peters code he used “private” but if I
remove it, it actually works can someone explain the use of private
here, is this the way of making a private def in Ruby?
You make methods private if you don’t want to expose them on the
object’s public API. Note that because of Ruby’s dynamic nature,
‘private’ does not mean that you can’t call the method from the
outside, it just discourages it. Ruby enforces that private methods can
only be called without an explicit receiver, i.e., you can not call it
with a dot directly in front of it. If ‘calc’ is a private method of
Class A, then you cannot do this:
A.new.calc # => fails
However, inside of an instance of A, you can call calc without
specifying a receiver (because self will be used implicitly). If you
still want to call a private method from the outside, the common way is
to use #send. Therefore, you could do this:
A.new.send(:calc)
Typically, you will make methods private if you don’t intend them to be
called from the outside. Use them to express your intentions more
clearly and help others (or your future self) to understand your code
better.