[RUBY] 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
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
Speed improvement tips with a little tech
I tried playing with BottomNavigationView a little ①
A story packed with Java's standard input Scanner
The story of making a reverse proxy with ProxyServlet
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 story packed with the basics of Spring Boot (solved)
A confused story about a ternary operator with multiple conditional expressions