0

i'm trying to learn ruby, i have this code.

#!/usr/bin/ruby

randomNumber = 5

class Testing
  def self.add
      puts randomNumber * 6
  end
end

Testing.add

And i get the error "Undefined local variable or method 'randomNumber'... But i have defined it .. so i thought, with the randomNumber = 5 .. i've tried int randomNumber = 5 but still no help. I have a feeling my oop sucks and i need to do more reading but i just don't get why this isn't working. Thanks for any help

2
  • 1
    Why would you think randomNumber is in scope for the Testing class? Commented Oct 14, 2014 at 3:57
  • @CodeGnome because he's obviously coming from JavaScript. Look at the naming conventions too. Commented Oct 14, 2014 at 4:09

1 Answer 1

2

Ruby doesn't work like javascript

class Testing

  # define a class variable
  @@random_number = 5

  # "add" class method
  def self.add
    puts @@random_number * 6
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

My bad, it is $ isn't it :P Never used global variables in Ruby.
This isn't a global variable ! It's a class variable !
why not use a class instance variable (@) over a class variable (@@)? or a constant (screaming_snake_case)?
@astreal Because class variables are entirely appropriate for this case and are easier to use.

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.