What is the equivalent of "from" and "import" (PYTHON) in Ruby?

Asked

Viewed 458 times

1

I would like to call a script through another script. In Python I use the commands "from" and "import", but which command would be equivalent to do this in Ruby?

1 answer

2


To include modules, classes, etc in other files you have to use the require_relative or require (require_relative is a more "rustic" way of programming. ) For example the following module:

module Format

  def cor_verde(input)
    puts"\e[32m#{input}[0m\e"
  end
end

So you have the following file:

require_relative "format" #<= "pede" o arquivo

include Format #<= inclui o módulo

def exemplo
  cor_verde("Essa frase vai ser verde") #<= chama a formatação
end

The same thing for classes:

class Exemplo

  attr_accessor :input

  def initialize(input)
    @input = input
  end

  def prompt
    print "#{@input}: "
    gets.chomp
  end
end

exemplo = Exemplo.new(ARGV[0])

And then the main file:

require_relative "class_exemplo"

exemplo.prompt

To call any class or module from another file you have to give the require.

  • 1

    +1! A small note: when using Ruby on Rails, everything is inside the subfolders of app/ is automatically required by default (with some exceptions), without calling require.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.