Ruby: What is the method for later definition?

I am trying to write a small ruby ​​script that will have two methods ( TrySlot and LookAtCut ). Each method should be able to call a different method. When a ruby ​​parses the first method, it fails because it does not understand the name of the second method, since I have not defined it yet.

So, how can I tell ruby, there is a method called TrySlot , which I will define later, so I can call TrySlot in my definition for LookAtCut ?

+4
source share
1 answer

The reason you get the problems is because Ruby usually accepts all names, starting with an uppercase letter, which is a constant. However, it will also allow you to define methods with a name starting with a capital letter. The following happens:

  • Ruby sees def LookAtCut and correctly defines a method called LookAtCut
  • Inside LookAtCut , Ruby sees TrySlot , assumes that it is a constant, tries to find it and fails with an error, since it is not defined.

The solution is to not use method names starting with uppercase characters. Then you can use a method that is not yet defined inside another:

 def a b end def b puts "Hello!" end a #=> "Hello!" 
+6
source

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


All Articles