Passing reference to a class


How to pass reference to a class in Ruby?

For example:-

def func(x)
x = x+1

a = 5
puts a



Classes are just constants.

def lol_factory(klass)

my_string = lol_factory(String)

On Tue, Jan 17, 2012 at 1:36 PM, Tridib B.
[email protected]wrote:

a = 5

Hi, it’s not clear how this code example has anything to do with a
reference to a class (I assume you mean class as in Array, String,

Anyway, classes are objects like anything else, they are accessed by
looking up the constants, but the constants are just references like
variables are, so you can do:

def instantiate(klass)

instantiate String # => “”
instantiate Array # => []
instantiate Hash # => {}

In this case, we name the variable “klass” because “class” is a keyword.

On 01/17/2012 01:36 PM, Tridib B. wrote:

a = 5
puts a

Instances of classes such as Fixnum, from your example, are immutable.
Your func method actually causes a new Fixnum instance to be created
whose value is 1 greater than the Fixnum instance passed in.

If you want to make a mutable number-like object that would work in your
example code, you’ll need to create your own wrapper object that
implements all the necessary methods of the number object you wish to
emulate. Take a look at the delegate library from the Ruby standard
library for something that might help you quickly whip up such a


On Tue, Jan 17, 2012 at 8:36 PM, Tridib B.
[email protected] wrote:

puts a

  1. func is not a class, it’s a method.
  2. Ruby is not C++.
  3. You cannot modify a variable because Ruby passes references by value.
  4. The assignment in func is superfluous as you do not use x any more
    after assignment.

What problem are you trying to solve?



hi Tridib,

if i’m not mistaken you could just do something like this:

class Fixnum
def add_one
self + 1

p 5.add_one

=> 6

…is that what you were looking for?

  • j