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..
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.
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.
In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.
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.
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 :)
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
To define a class variable, use an @@
:
class User
@@description = "I am a User class variable"
def print
puts @@description
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With