Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - constant initialisation with some function produces NoMethodError

Let's consider following code:

class Try
 CONST = xxx("42")

 private_class_method def self.xxx(str)
   str.to_i
 end
end

puts Try::CONST

It produces an error: undefined method `xxx' for Try:Class (NoMethodError)

It seems that I cannot use a class private method to initialise a constant. The example is doing nothig actually, but it is a reproduction of an error I am facing trying to read data from file into the class constant.

Is it becuse ruby tries to initialize a constant before it get know about all methodes, or am I doing something wrong?

like image 348
Koikos Avatar asked Apr 20 '26 08:04

Koikos


1 Answers

Not really. What you can't do is to assign the value of something that still hasn't been defined to something else in order to hold its value.

It has nothing to do with the method visibility because this works:

class Try
  private_class_method def self.xxx(str)
    str.to_i
  end
  CONST = xxx("42")
end

p Try::CONST
# 42
like image 92
Sebastian Palma Avatar answered Apr 22 '26 00:04

Sebastian Palma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!