Kristoff vdH
Kristoff vdH

Reputation: 234

bizarre behavior of system() in Ruby

I have set up shuffle_play.rb in Ruby by Example to work on Windows, with mpg123 instead of ogg123. The critical part is a method called play_file, which initially I wrote like this

def play_file(file)
  system("mpg123 \"#{file}\"")
end

I have mpg123 in the same directory as my script ... it didn't work. But this does work:

def play_file(file)
  system("mpg123.exe \"#{file}\"")
end

I reckon it's because I don't have working directory in %PATH% (and indeed the problem goes away when I add it) but even then I don't know enough about Windows to know the difference. Could someone explain the rationale for this?

Upvotes: 0

Views: 136

Answers (1)

Augusto
Augusto

Reputation: 29927

Probably the examples assume that you're on a *nix variant such as Linux or Mac. In those Operating Systems, the program is called mpg123, because those OS, don't care about extensions, the just check that the file has an executable attribute

On windows things are very different. Windows decides if something is a program depending on the extension (.exe, .com, .bat, .cmd, etc.). So the program in windows has to be called mpg123.exe. If you open a command line on windows, you can run the program without specifying the extension, as windows automatically tries the different extensions. This behaviour of trying different extensions happens ONLY in the command line and not when you try to invoke a program from another one.

There a environment variable called PATHEXT that list in which order windows tries the different extensions. On my computer that list is:

C:\Windows\System32>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.RB;.RBW

I hope it was clear. And a suggestion if you want to code in ruby, install Linux or get a Mac.

Upvotes: 3

Related Questions