How to execute a Ruby script in Terminal?

前端 未结 9 1593
南笙
南笙 2020-12-04 06:15

I\'ve set everything up that I need on my Mac (Ruby, Rails, Homebrew, Git, etc), and I\'ve even written a small program. Now, how do I execute it in Terminal? I wrote the pr

相关标签:
9条回答
  • 2020-12-04 06:55

    In case someone is trying to run a script in a RAILS environment, rails provide a runner to execute scripts in rails context via

    rails runner my_script.rb

    More details here: https://guides.rubyonrails.org/command_line.html#rails-runner

    0 讨论(0)
  • 2020-12-04 06:56

    Assuming ruby interpreter is in your PATH (it should be), you simply run

    ruby your_file.rb
    
    0 讨论(0)
  • 2020-12-04 07:00

    Just call: ruby your_program.rb

    or

    • start your program with #!/usr/bin/env ruby,
    • make your file executable by running chmod +x your_program.rb
    • and do ./your_program.rb some_param
    0 讨论(0)
  • 2020-12-04 07:00

    Although its too late to answer this question, but still for those guys who came here to see the solution of same problem just like me and didn't get a satisfactory answer on this page, The reason is that you don't have your file in the form of .rb extension. You most probably have it in simple text mode. Let me elaborate. Binding up the whole solution on the page, here you go (assuming you filename is abc.rb or at least you created abc):

    Type in terminal window:

    cd ~/to/the/program/location
    ruby abc.rb
    

    and you are done

    If the following error occurs

    ruby: No such file or directory -- abc.rb (LoadError)
    

    Then go to the directory in which you have the abc file, rename it as abc.rb Close gedit and reopen the file abc.rb. Apply the same set of commands and success!

    0 讨论(0)
  • 2020-12-04 07:07

    Open your terminal and open folder where file is saved.
    Ex /home/User1/program/test.rb

    1. Open terminal
    2. cd /home/User1/program
    3. ruby test.rb

    format or test.rb

    class Test 
      def initialize
       puts "I love India"
      end
    end
    
    # initialize object
    Test.new
    

    output

    I love India
    
    0 讨论(0)
  • 2020-12-04 07:08

    Just invoke ruby XXXXX.rb in terminal, if the interpreter is in your $PATH variable.

    ( this can hardly be a rails thing, until you have it running. )

    0 讨论(0)
提交回复
热议问题