How can I access a variable defined in a Ruby file I required in IRB?
Asked Answered
A

4

20

The file welcome.rb contains:

welcome_message = "hi there"

But in IRB, I can't access the variable I just created:

require './welcome.rb'

puts welcome_message 

# => undefined local variable or method `welcome_message' for main:Object

What is the best way to bring in predefined variables and have initialization work done when you require something into your IRB session? Global variables don't seem like the right path.

Ammonium answered 23/4, 2010 at 14:27 Comment(0)
X
18

While it is true that you cannot access local variables defined in required files, you can access constants, and you can access anything stored in an object that you have access to in both contexts. So, there are a few ways to share information, depending on your goals.

The most common solution is probably to define a module and put your shared value in there. Since modules are constants, you'll be able to access it in the requiring context.

# in welcome.rb
module Messages
  WELCOME = "hi there"
end

# in irb
puts Messages::WELCOME   # prints out "hi there"

You could also put the value inside a class, to much the same effect. Alternatively, you could just define it as a constant in the file. Since the default context is an object of class Object, referred to as main, you could also define a method, instance variable, or class variable on main. All of these approaches end up being essentially different ways of making "global variables," more or less, and may not be optimal for most purposes. On the other hand, for small projects with very well defined scopes, they may be fine.

# in welcome.rb
WELCOME = "hi constant"
@welcome = "hi instance var"
@@welcome = "hi class var"
def welcome
  "hi method"
end


# in irb
# These all print out what you would expect.
puts WELCOME
puts @welcome
puts @@welcome
puts welcome
Xerophyte answered 23/4, 2010 at 15:54 Comment(1)
Nice, as an comment: The WELCOME in John Hyland's code can be accessed because it started by upcase letter, this make it a constant. Ruby is interest.Plassey
H
4

You can't access local variables defined in the included file. You can use ivars:

# in welcome.rb
@welcome_message = 'hi there!'

# and then, in irb:
require 'welcome'
puts @welcome_message
#=>hi there!
Helyn answered 23/4, 2010 at 15:17 Comment(0)
K
3

That should at least enable the experience from irb:

def welcome_message; "hi there" end
Kure answered 23/4, 2010 at 15:15 Comment(0)
M
2

I think the best way is to define a class like this

class Welcome
  MESSAGE = "hi there"
end

then in irb you can call your code like this :

puts Welcome::MESSAGE
Mountfort answered 23/4, 2010 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.