A little addictive story with def initialize

In initialize, the value is set when new

I was addicted when I wanted to refer to the value set in initialize in the class method

class Hoge
  attr_accessor :aa
  def initialize
    @aa = 'aa'
  end
  def self.bb
    @aa
  end
end

p Hoge.bb
# => nil

I haven't set the value because I haven't done Hoge.new, So nil is returned

class Hoge
  attr_accessor :aa
  def initialize
    @aa = 'aa'
  end
  def bb
    @aa
  end
end

hoge = Hoge.new
p hoge.bb

You can refer to the value by using the instance method (it is natural) When you want to use a value in a class method Let's set the value directly to the instance variable without using initialize.

class Hoge
  @aa = 'aa'
  def self.bb
    @aa
  end
end

p Hoge.bb
#=> "aa"

Whether to use it in a class method or an instance method I was addicted to learning that I had to be aware of the contents of initialize according to the purpose.

Dedicated every day

Recommended Posts

A little addictive story with def initialize
I tried playing with BottomNavigationView a little ①
A little addictive story with def initialize
A story stuck with NotSerializableException
A little regular expression story Part 1
A little regular expression story Part 2
A little troublesome story in Groovy
A little addictive story after updating the JDBC driver for PostgreSQL
I tried playing with BottomNavigationView a little ①
A story packed with Java's standard input Scanner
[PHP] A story about outputting PDF with TCPDF + FPDI
A story about trying to get along with Mockito
A story about reducing memory consumption to 1/100 with find_in_batches
A story about developing ROS called rosjava with java
Story of making a task management application with swing, java
A confused story about a ternary operator with multiple conditional expressions