I\'m new to coding and new to learning the language Ruby. I\'ve made progress on my code of a letter histogram. I\'m now at a point where I\'m struggling.
class
Good start :)
In order to make a method private, place it after a call to private in the class:
class foo
# all methods are public by default
def something_public
# …
end
private
# makes all methods after this call private
def something_internal
# …
end
end
Alternatively, you can call private with the symbol name of the method you want to make private (after it has been defined): private :something_internal. In newer versions of ruby defining a method returns the method name (as a symbol), so you can also do this:
private def something_internal
# …
end
to make just the one method private.
In ruby, "private" means that you can't call the method with a dot, e.g. foo.something_internal will raise a NoMethodError if something_internal is a private method on foo. That means that to call a private method, you need to be in a method in the same class:
class foo
# …
def something_public
if something_internal # method called without a dot
'the internal check was truth'
else
'the internal check was falsey'
end
end
# …
end
Private methods are usually used to create helpers for the class that don't make sense to be called from outside the class, or that can cause bugs if they are called at the wrong time. In ruby, you can call a private method anyway if you really want by using send: foo.send(:something_internal, 'some', 'arguments'). But generally, you shouldn't need to, and you should rethink your code and see if you can refactor it to not need to call send.
Also, by convention in ruby, method names are snake_cased and usually don't start with a capital (although the language allows this).