The best way to organize a long piece of code in a ruby ​​processing block

module Access
  def last
    self[-1]
  end

  def start_end
    self[0] + last
  end
end

module StringExt
  refine String do
    include Access
  end
end

using StringExt

puts 'abcd'.last       # => d
puts 'abcd'.start_end

When a class is cleared by too many related methods, I think it is better to extract them into a module. However, in the above example, which demonstrates the problem when one method calls another (see the Last statement), and it causes the following error.

in 'start_end': undefined local variable or method 'last' for "abcd": String (NameError)

A similar problem was solved using a global variable, which also works for my example. But I'm looking for another better way to organize advanced interpreted methods and avoid the global thing.

How to advise the best way to organize these methods?

+4
1

, . . , /. :

module StringPatches

  def self.non_empty?(string)
    !string.empty?
  end

  def non_empty?
    StringPatches.non_empty?(self)
  end

  def non_non_empty?
    !StringPatches.non_empty?(self)
  end

  refine String do
    include StringPatches
  end

end

class Foo
  using StringPatches
  puts "asd".non_empty? # => true
  puts "asd".non_non_empty? # => false
end

StringPatches using. / (), .

+3

Source: https://habr.com/ru/post/1673483/


All Articles