Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ruby how to use class level local variable? (a ruby newbie's question)

Tags:

ruby

So suppose I have this (not working):

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

So, how should I use the var description, how to pass this into a method as a default parameter, or used in the method directly? Thanks..

like image 473
user875883 Avatar asked Sep 27 '11 16:09

user875883


People also ask

How do you use local variables in Ruby?

A local variable is only accessible within the block of its initialization. Local variables are not available outside the method. There is no need to initialize the local variables. Instance Variables: An instance variable name always starts with a @ sign.

How do I use a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

What does @variable mean in Ruby?

In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.

How do you initialize a variable in Ruby?

Global variables start with dollar sign like. For Instance Variables: Instance variables can be initialized with @ symbol and the default value for it will be nil.


3 Answers

You can access the class-scope using define_method.

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

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

I don't think it's good idea, though :)

like image 194
cutalion Avatar answered Nov 15 '22 22:11

cutalion


In your case, the description is only local variable. You can change this scope using 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 might be using by 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
like image 33
evfwcqcg Avatar answered Nov 15 '22 21:11

evfwcqcg


To define a class variable, use an @@:

class User
   @@description = "I am a User class variable"

   def print
       puts @@description
   end
end
like image 26
Jacob Relkin Avatar answered Nov 15 '22 21:11

Jacob Relkin