Open the default browser in Ruby

Viewed 27777

In Python, you can do this:

import webbrowser
webbrowser.open_new("http://example.com/")

It will open the passed in url in the default browser

Is there a ruby equivalent?

9 Answers

Cross-platform solution:

First, install the Launchy gem:

$ gem install launchy

Then, you can run this:

require 'launchy'

Launchy.open("http://stackoverflow.com")

Mac-only solution:

system("open", "http://stackoverflow.com/")

or

`open http://stackoverflow.com/`

Simplest Win solution:

`start http://www.example.com`

This also works:

system("start #{link}")

Windows Only Solution:

require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute(...)

Shell Execute on MSDN

You can use the 'os' gem: https://github.com/rdp/os to let your operating system (in the best case you own your OS, meaning not OS X) decide what to do with an URL.

Typically this will be a good choice.

require 'os'

system(OS.open_file_command, 'https://stackoverflow.com')
# ~ like `xdg-open stackoverflow.com` on most modern unixoids,
# but should work on most other operating systems, too.

Note On windows, the argument(s?) to system need to be escaped, see comment section. There should be a function in Rubys stdlib for that, feel free to add it to the comments and I will update the answer.

Related