47

I'm making a small ruby command line script and I wanted to know what the simplest way to have the program emit a beep is.

5 Answers 5

72

Try printing the audible bell character:

print "\a"
4
  • 1
    How do I customize this beep sound? I want to play a different beep sound than the default one. Thanks
    – Prabhakar
    Nov 25, 2017 at 13:25
  • You can't, these are ansi escape codes to control the terminal - but maybe you could play beeping and sleeping in between to produce different sequences.. checkout en.wikipedia.org/wiki/…
    – cancerbero
    Jan 22, 2020 at 10:51
  • interestingly, this only results in one beep for me: 3.times { print "\a\a\a"; sleep 3 } 🤷‍♀️
    – MustModify
    Dec 9, 2021 at 15:43
  • multiple beeps prevented for me by my SSH client (putty).
    – MustModify
    May 25, 2022 at 13:40
42

For Mac OS X:

system('say "beep"')

Conventional print "\a" didn't always work by some reason for me (MBA, 10.7.4)

2
  • 4
    That's certainly a way to do it. Jul 6, 2012 at 18:39
  • make sure you use double quotes and you are in a real terminal - worked in macos default terminal, iterm2 also in linux terminals . In macos, if you have volume === 0 then the screen flashes since laptops seem to use sound card for beeping and not internal speaker as good old desktop PCs. It didn't work on a PTY like in the vscode terminal - it should work on tmux, or ssh sessions I think. Not sure about windows terminals - probably works on git shell cygwin, etc
    – cancerbero
    Jan 22, 2020 at 10:49
12

For windows, use the win32-sound gem - Adding Sound to Your Ruby Apps.

To install:

gem install win32-sound

Then in Ruby:

require 'win32/sound'
include Win32
...
Sound.beep(100, 500)

For non-windows, looks like this could work: How to make beep sounds?

puts 7.chr
1
  • 3
    You could save valuable bytes on that last one by doing putc 7. Do your part to address the byte shortage! Feb 4, 2016 at 19:26
5

The easiest way is puts 7.chr

Here is a customize way

require "Win32API"
Beep = Win32API.new("kernel32", "Beep", ["I", "I"], 'V')
def beep freq, duration
  Beep.call(freq, duration)
end 

beep 600, 400
-2

Try the following:

$stdout.beep
4
  • 1
    That didn't work for me, what version of Ruby is it in and is it document anywhere? Feb 4, 2016 at 19:56
  • I think you need to have an apple macintosh. I tried on a linux ssh and it failed. And surely it wouldn't work on Windows or HaikuOS. Feb 4, 2016 at 20:56
  • 1
    Nope, it's not a Mac thing. Jun 28, 2016 at 19:59
  • Works in Ruby 2.6 on macOS Catalina. May 14, 2021 at 14:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.