Why won't my Ruby script execute?

橙三吉。 提交于 2020-01-02 23:14:30

问题


So, I made a simply ruby script,

#!/usr/bin/env ruby

puts "Hello!"

When I try to run it in terminal it doesn't put "Hello!" on the screen. I have tried entering chmod +x test.rb (test.rb is the name of my file). When I run it, it doesn't give me an error, it just doesn't display "Hello!". Any help will be much appreciated. I have looked everywhere for a possible answer, and I have found nothing so far.


回答1:


I'd guess that you're trying to run it as just test like this:

$ test

But test is a bash builtin command that doesn't produce any output, it just sets a return value. If you run your script properly:

$ ./test.rb

then you'll see something. Note the explicit ./ path, the current directory is rarely (and hopefully never) in your PATH so you need to say ./ to run something in the current directory (unless of course you're in /bin, /usr/bin, etc.).


In the comments you say that there are some Ctrl+M characters in your script:

$ cat -e test.rb
#!/usr/bin/env ruby^M^Mputs "Hello!"

I don't see any $s in that cat -e output so you don't have any actual end-of-line markers, just some carriage-return characters (that's the ^M). A single CR is an old MacOS end-of-line, Windows uses a CR-LF pair, and Unix (including OSX) uses just a single LF to mark the end of a line of text. Since you don't have any EOLs, the shell just sees a single line that looks like:

#!/usr/bin/env ruby ...

without an actual script for ruby to run, the shell just sees the shebang comment and nothing else. The result is that nothing noticeable happens when you run your script. Fix your EOLs and your script will start working sensibly. You might also want to look at your editor's settings so that it starts writing proper EOLs.




回答2:


How are you calling this method. You would want to call this out by something like ruby test.rb if you are in the directory with the test.rb file. Another general tip for trying something out that doesn't work would be to go into irb on command line and try your program, like puts "Hello! to see if it is that particular code that is the problem.



来源:https://stackoverflow.com/questions/18705194/why-wont-my-ruby-script-execute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!