Ruby Scripting language
Light · Postcard
102 × 152 mm · PDF
Dark · Postcard
102 × 152 mm · PDF
Ink saver · Postcard
102 × 152 mm · PDF
Light · A4 landscape
297 × 210 mm · PDF
Dark · A4 landscape
297 × 210 mm · PDF
Ink saver · A4 landscape
297 × 210 mm · PDF
Light · A3 landscape
420 × 297 mm · PDF
Dark · A3 landscape
420 × 297 mm · PDF
Ink saver · A3 landscape
420 × 297 mm · PDF
Start here
ruby -e '<code>'
ruby <file>.rb
irbruby -c <file>.rb
ruby -w <file>.rb
gem install <name>
ruby -n -e '<code>'
bundle exec <cmd>
Concepts
- Input line stdin or files
- $_ current line
- Output -p prints $_
Running ruby
ruby -e '<code>'
ruby <file>.rb [args]
ruby -vruby -c <file>.rb
ruby -w <file>.rb
ruby -r <lib> -e '<code>'
ruby -I <dir> <file>.rb
ruby -n -e '<code>'
ruby -p -e '<code>'
ruby -lane 'puts $F[0]'
ruby -i.bak -pe '<code>' <file>
irb
irbls <obj>show_doc <Class#method>
show_source <Class#method>
binding.irbGems
gem install <name>
gem install <name> -v <version>
gem install <name> --user-install
gem listgem search <regexp>
gem uninstall <name>
gem outdatedgem update <name>
Syntax
puts <x>p <x>name = "#{first} #{last}"
def <name>(a, b = 1, *rest, k:, **opts)
if <a> ... elsif ... else ... end
x = cond ? a : b
<obj>&.<method>
x ||= <default>
case x when 1..5 then ... else ... end
3.times { |i| ... }
:name %i[a b]{ a: 1, "b" => 2 }
->(x) { x + 1 }.call(2)
&:upcaseyield / block_given?
Strings & output
format("%05.1f %s", 3.14159, "x")
str.split(",")
str.gsub(/<re>/, "<new>")
str.strip / chomp
Collections
arr.each { |x| ... }
arr.map { |x| x * 2 }
arr.select { |x| x.even? }
arr.reduce(0) { |sum, x| sum + x }
arr.sort_by { |x| x.size }
arr.group_by { |x| x.size }
arr.each_with_index
arr.each_with_object({}) { |x, h| ... }
arr.find { |x| ... }
arr.tallyh.fetch(:k)h.fetch(:k, <default>)
h.dig(:a, :b)h.each { |k, v| ... }
h.transform_values { |v| ... }
Pattern matching
case x in { name: String => n, age: } ... end
case x in [a, *rest] ... end
in Integer | Float => n
<expr> => { name: }
<expr> in { role: :admin }
Classes, Struct & Data
class <Name> ... end
attr_reader :a / attr_accessor :a
def initialize(a) ; @a = a ; end
class B < A ; super ; end
Point = Struct.new(:x, :y)
Point = Data.define(:x, :y)
pt.with(x: 5)Errors & requires
begin ... rescue Err => e ... ensure ... end
raise ArgumentError, "<msg>"
rescue => erequire "<lib>"
require_relative "<path>"
ARGV / ENV["<VAR>"]
File.read("<f>") / File.readlines
Recipes
# values separated by spacesruby -lane 'BEGIN{s=0}; s += $F[1].to_f; END{puts s}' data.txt
ruby -i.bak -pe 'gsub(/foo/, "bar")' *.txt
curl -s <url> | ruby -rjson -e 'puts JSON.pretty_generate(JSON.parse($stdin.read))'
ruby -run -e httpd . -p 8000



