14

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..

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

It's good that you showed defined? a, but he asked how to use a local variable .. and if you use @ or @@ or $ then your own answer suggests it's not a local variable. Therefore it's not answering the question. The great info you provide in your answer suggests that local variables are not local to the class.
6

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 :)

Comments

1

To define a class variable, use an @@:

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

   def print
       puts @@description
   end
end

Comments

0

Instance variables must be prefixed with an @ and are not accessible from outside. Class variables must be prefixed with an @@.

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

attr_reader :description

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

3 Comments

attr_reader works only for instance variables, not class variables. If you are using Rails, you can use cattr_reader to do this.
but I saw a code example use a variable like I did, so is it legal?
@user875883 That would be a strange code example. Maybe it was about showing how a local variable defined on the class level is NOT in scope inside the methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.