Ruby Equivalent of C# 'using' Statement
Asked Answered
F

2

6

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.

Fatimafatimah answered 3/12, 2009 at 4:55 Comment(3)
I think you are asking about using var1=System.Collections; Basically creating an alias for a namespace so that var1 can be used instead of it. Am I right?Effulgence
My bad, I wasn't even thinking about the alias usage of 'using'... or even the disposing code block feature of 'using'... geeh, C# sure loves the 'using' keyword.Fatimafatimah
Sorry for misunderstanding. I got it now, you want to include a library in your code.Effulgence
P
6
>> 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.

Parton answered 3/12, 2009 at 5:2 Comment(1)
Thanks! The include keyword was what I was after.Fatimafatimah
S
1

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"
Socalled answered 3/12, 2009 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.