Every Ruby journey starts with running code and inspecting values, and IRB is where Rubyists experiment.
Ruby code lives in .rb files and runs with ruby hello.rb. For experiments, start IRB, the interactive Ruby shell, with irb: type an expression and it prints the result. ruby -e 'puts 1 + 1' runs a one-liner, and ruby -v shows the version.
Three ways to print:
puts xprintsx.to_sfollowed by a newline (arrays print one element per line).print xprints without a newline.p xprintsx.inspect, the developer view: strings keep their quotes, andnilis shown asnil. It also returns its argument, so you can wrap it around an expression while debugging.
In Ruby everything is an object, including numbers, nil and true. You call methods on them with a dot: 5.even?, "ruby".upcase, nil.to_a. Even 1 + 2 is the method call 1.+(2).
Comments start with #. Parentheses around method arguments are optional (puts "hi" and puts("hi") are the same), and statements end at the line break, without semicolons.
By convention, methods ending in ? return a boolean (empty?), and methods ending in ! are the "dangerous" version of a method, usually one that modifies the receiver in place (upcase!).
Example
# hello.rb: run with `ruby hello.rb`
puts "Hello, Ruby!" # Hello, Ruby!
puts RUBY_VERSION # e.g. 3.4.7
p "quoted" # "quoted"
puts nil.inspect # nil
puts 5.even? # false
puts "ruby".upcase # RUBY
puts 1.+(2) # 3: operators are methods
puts 42.class # Integer
puts nil.class # NilClassRemember
- Run files with ruby file.rb and experiment in irb
- puts shows to_s, p shows inspect (great for debugging)
- Everything is an object; operators are method calls
Watch out for
- Using puts to debug and missing that a value is nil or a string; use p instead.