Delgan
Delgan

Reputation: 19677

Require a library in Ruby using a function which returns the library, like Python __import__()?

Usually in Ruby, we would do something like this when importing a built-in library:

require "prime"
puts Prime.prime?(42)

In Python, it would look like this:

import math
print(math.pi)

However, there is also a function to do this in one line:

print(__import__("math").pi)

I would like to know if such a function exists in Ruby.

Upvotes: 1

Views: 59

Answers (1)

Holger Just
Holger Just

Reputation: 55888

In Python, the name of the module is directly derived from the filesystem path. This allows it to import and return the module at the same time using the same name.

In Ruby however, this connection can not be assumed. While it is good practice to specify a single module or class in a file with the the same name as the filename (after snake_case to CamelCase translation), this is not enforced nor it is always given.

In Ruby, a file is just a container of code. You can define multiple classes or modules in a single file or even re-open existing ones. As such, when requiring (i.e loading) a file and running its content, you can't know that the result will be a single module or class. In fact, the return value of require is explicitly undefined.

Thus, to summarise, this is not possible in Ruby as the assumptions required for this to work are not enforced in Ruby.

Upvotes: 1

Related Questions