Stepping through helloworld.rb

Now that we know the theory behind this, let's clarify by walking through the example helloworld.rb program.

require 'gtk'

Loads the Gtk bindings.

window =
button ="Hello World")
window.set_title("Hello Ruby")

Create a new window and a new button. Then set the title and border width of the window.

# Connect the button to a callback.
button.signal_connect('clicked') { puts "Hello Ruby" }

Here we connect the button to a signal handler. When the button is clicked, a "clicked" signal is sent, and the callback is excecuted.

# Connect the signals 'delete_event' and 'destroy'
window.signal_connect('delete_event') {
	puts "delete_event received"
window.signal_connect('destroy') {
	puts "destroy event received"

Here we have two more examples of callbacks. These two also help show the difference between a delete_event signal and a destroy signal.

When you try to close a window, the X server sends a delete_event signal. You then associate this signal with a function. If this function returns true the window is NOT closed. This can be useful to popup "are you sure that you want to quit?". If the function returns false , Gtk+ proceeds to send a destroy signal. The destroy signal can be attached to a callback, but it always destroys the window.


Make sure that you understand the difference between a delete_event and a destroy signal. Change the false above by true and try closing the window.

window.add button

You need to add the button to the window. Otherwise it will not show.


window.show_all displays the window, and all its contents. In contrast, the show method only displays the widget it's called upon. Alternatively, we could have written

But that would get cumbersome very quickly.


This enters the Gtk main loop.