In ruby, how to use a local class level variable? (question about the new ruby)

So, suppose I have this (doesn't work):

class User description = "I am User class variable" def print puts description end end 

So, how should I use the var declaration, how do I pass this to the method as the default parameter, or use it directly? Thanks..

+6
source share
4 answers

In your case, description is just a local variable. You can change this area with the special characters @ , @@ , $ :

 a = 5 defined? a => "local-variable" @a = 5 defined? @a => "instance-variable" @@a = 5 defined? @@a => "class variable" $a = 5 defined? $a => "global-variable" 

For your purpose, I think it can be used this way.

 class User def initialize(description) @description = description end def print puts @description end end obj = User.new("I am User") obj.print # => I am User 
+4
source

You can access the class using define_method .

 class User description = "I am User class variable" define_method :print do puts description end end 

User.new.print
I am a user class variable
=> nil

I don't think this is a good idea though :)

+2
source

To define a class variable, use @@ :

 class User @@description = "I am a User class variable" def print puts @@description end end 
+1
source

Instance variables must have the @ prefix and are not accessible externally. Class variables must be prefixed with @@ .

The first time you use this variable anywhere in the code, it will be initialized. If you want to access the value from outside:

 attr_reader :description 

http://rubylearning.com/satishtalim/tutorial.html

0
source

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


All Articles