Take this code, for example:
class Stack def initialize @array = [] end def push val @array.push val end def pop @array.pop end end
Here you have a private instance of var to which you delegate the selected methods. Other methods cannot be called directly. The syntax can be sweetened and made more "rubesque" with some metaprogramming, but the basic idea is as shown above.
Of course, you can always get to this private var via instance_variable_get , and there is nothing you can do about it. This is Ruby!
Make a clean, secure public interface. And if someone tries to interfere in the internal parts and breaks something, this is his problem.
Update
If you are using ActiveSupport (which comes with Rails), then there is an easier way to do this.
# load ActiveSupport if not in Rails env require 'active_support/core_ext' class Stack def initialize @impl = [] end
Or see a similar answer from @AndrewGrimm.
source share