Shashi Ranjan
Shashi Ranjan

Reputation: 1561

Access variables in self.method in ruby script

I am very new to ruby. I am facing issue in getting the variable value in self.method

My ruby class/script look like this:

class A1
  def initialize
    @myUtil = MyUtil.new log
    @test_hash = @myUtil.loadPropertiesFile(File.dirname(__FILE__) + '/my-tests.properties')
  end

  def self.testCases
    tests = {}

    @test_hash.each do |k, v|
        puts "#{k}"
    end

    tests
  end

  def launch test, testbed, h = {}

    @test_hash.each do |k, v|
        puts "#{k}"
    end

  end
end

I am able to print value in @test_hash in launch method but not in self.testCases. Where I am making the mistake?

Upvotes: 4

Views: 896

Answers (2)

davidhu
davidhu

Reputation: 10434

I see a few errors in your code.

  • In your initialize method, you created a global variable $test_hash, anytime you put a $ in front of a variable, it becomes available everything. That is not something you want to do in this case. An instance variable would work best for you in this case.

  • Your testCases method is a class method, which means you can call it without creating a new instance of the class, ie A1.new. So you call the method like A1.testCases (Ruby uses snake case for method names, test_cases, just fyi). You initializes the test_hash variable in the initialize method, which does not automatically gets call until you create a new instance of the class. Therefore, test_hash does not exist when you simply run 'A1.testCases`.

  • for the line puts "#{k}" is not good practice. puts stands for put string, and it will automatically convert the variable into a string. You should use puts k. the #{} is meant for string interpolation. Such as "Hi, my name is #{name}, and I am #{age} years old."

Here's how I would do this. I replaced the test_hash with a simple hash for testing purposes.

class A1
  def initialize
    @test_hash = {a: 1, b: 2, c: 3, d: 4, e: 5}
  end

  def testCases
    @test_hash.each do |k, v|
        puts k
    end
  end
end

Now, you create a new instance of A1 and call the testCases method (now an instance method, instead of a class method)

A1.new.testCases

Upvotes: 3

maicher
maicher

Reputation: 2745

The hard part is to understand, that in Ruby classes are also object. So a1 = A1.new is an object and A1 is also an object.

By using @ inside initialize, you create an instance variable belonging to a1 = A1.new object.

By using @ inside self.testCases method, you create instance variable belonging to A1 object.

Upvotes: 2

Related Questions