views:

110

answers:

2

I've been getting into Ruby over the past few months, but one thing that I haven't figured out yet is what the Ruby equivalent of C#'s (and other languages) using statement is.

I have been using the require statement to declare my dependencies on Gems, but I am getting lazy and would prefer to not fully qualify my frequently used class names with their module (namespace) name.

Surely this is possible, right? I must not be using the right terminology as Google hasn't given me anything useful.

+1  A: 
>> Math::PI
=> 3.14159265358979
>> PI
NameError: uninitialized constant PI
    from (irb):3
>> include Math
=> Object
>> PI
=> 3.14159265358979

OTOH, if the issue is just aliasing class names, consider that, as they say "Class is an object, and Object is a class".

So:

>> require 'csv'
>> r = CSV::Reader
>> r.parse 'what,ever' do |e| p e end
["what", "ever"]

Yes, in Ruby the class name is just a reference like any other to an object of class Class.

DigitalRoss
Thanks! The `include` keyword was what I was after.
Jason Whitehorn
A: 

I don't believe there is a direct syntactic mapping. You can probably approximate it though since you can assign variables references to just about everything, including modules and classes.

module UsingExampleNamespace
    module SubExampleNamespace
        CON = "STANT"
    end
end

sen = UsingExampleNamespace::SubExampleNamespace
puts sen::CON
>> "STANT"
segy