Ruby (Wikipedia) is perhaps nice.
See online docs, ri
on your local system, or e.g.
RubyLearning.com, from which this page is cherrypicked.
This is mainly meant for myself, because my memory is that of a goldfish. The text loosely follows the order on the original web-page. I'll try to keep it short enough to be readable "in one go", so sections/chapters are hopefully not necessary.
Ruby programs normally get the .rb
extension
parenthesis when calling functions are usually optional
common methods puts
and gets
are members of the Kernel
module ("everything is an object"), and
available because an object main
of class Object
is automatically created at program start
comments: #
to end of line, or =begin
... =end
for comment-blocks
semicolon at end of line is optional
everything except false
or nil
, e.g. the number 0 or the empty string is considered true
_
can be used as thousands-separator, e.g. 1_000_000
Object
<-- Numeric
<-- { Integer
, Bignum
, Float
}
not
, or
and and
are logical operators with low precedence
expression modifiers (if
, unless
, while
, until
) have low precedence
range literals: ..
is inclusive, and ...
is exclusive
logical assignment operators exist: ||=
, &&=
, etc. (for each binary operator)
fallback-value: @variable ||= "default value"
single quoted strings only interpret `` to escape backslash or single quote
capture shell-output: backticks
lauch shell-command: system "ls -al"
(returns true
iff execution succeeded)
explicit conversions: to_i
, to_a
, to_s
HERE-doc: <<ENDMARKER
global variables: $globalvar
, e.g. $0
= name of executed file
instance variables: @instancevar
class variables: @@classvar
stdin input: gets
(including newline), chomp
removes newline, e.g. gets.chomp
naming-convention:
self
is the current/implicit object
method def.:
def my_method arg1, arg2
...
end
or
def my_method( arg1, arg2 )
...
end
string interpolation: "... #{
expr } ..."
default method args: def my_method arg1, arg2=42
splat operator:
def foo *args
puts "you gave #{ args.length } args"
end
rdoc
indexes Ruby- of C-files, and ri
reads these docs from the CLI
ri
: use #
or ::
to unambiguate between instance- and class-methods:
ri Array
ri Array.sort
ri Hash#each
ri Math::sqrt
useful String
-methods:
upcase
downcase
capitalize
slice
(substring, using index, start+length, range or regex) string-equality: ==
tests on content, and Object::equal?
tests on object equality
array of words: %w{ this is cool }
instead of [ 'this', 'is', 'cool' ]
it's elsif
:-)
case
..when
..else
expressions:
leap = case
when year % 400 == 0 then true
when year % 100 == 0 then false
else year % 4 == 0
end
puts leap
case
..when
..else
expressions:
pass blocks to methods:
def call_block
yield 'hello', 99
end
and then
call_block { |str, num| puts str + ' ' + num.to_s }
or
call_block do |str, num|
puts str + ' ' + num.to_s
end
block local variables:
5.times { |x, y; tmp1, tmp2| ... }
array literal: arr = [ 1, "two", :three ]
array-indices can be negative, with '-1' for the last array entry
delete 1 or more array-entries by value: arr.delete "the value"
useful array methods:
sort
length
( = size
)first
and last
each
(takes a block) ENV
is a hash with environment variables
ARGV
is an array with CLI args (0
for 1st arg)
ranges have an include?
method
symbols look like :my_sym
hash literal:
dutchify = { :green => "groen", :blue => "blauw" }
or (possible because keys are syms):
dutchify = { green: "groen", blue: "blauw" }
accessing hash-elements: h[ :green ]
(value of non-existing key is nil
)
reading a file:
File.open( 'input.txt', 'r' ) do |f1|
while line = f1.gets
puts line
end
end
writing to a file:
File.open( 'output.txt', 'w') do |f2|
f2.puts "plop."
end
(if no block is given, open
will simply open the file)
file-open modes: r
(r/o), w
(w/o, truncate), r+
(r/w)
read file into array, line by line: File.readlines
a regexp literal (class Regexp
) has the form /
regexp/
simple regexp test: /foo|bar/.match "frobozfoodtruck"
--> "foo" (class MatchData
)
class objects have their own methods (e.g. Dog::new
a.k.a. Dog.new
), NOT shared by
instances of that class (which have methods like Dog#bark
in written text - not code)
convert a block into a Proc
object using the lambda
method: greeter = lambda { |x| puts "hi #{ x }" }
Proc
objects can be called using greeter.call "there"
include (source) a Ruby script: load 'filename.rb'
include a module: require 'filename'
, for a module in filename.rb
some built-in modules:
some built-in classes:
String
objects have array-indexing" "foo"[ 0 ]
--> 'f'
list installed gems: gem list
list available remote gems: gem list --remote mysubstring
install a gem: gem install foobar
update all installed gems: gem update
create a generator (new value returned by each next
call):
e = Enumerator.new do |y|
y << 42
%w[ foo bar baz ].each { |s| y << s }
loop { y << 0 }
end
10.times { p e.next }
output:
42
"foo"
"bar"
"baz"
0
0
0
0
0
0
(running out of items results in a StopIteration
exception)
handling an exception:
begin
loop {
my_tricky_function 1, 2, "blue"
rescue StopIteration
return -1
end
(this example is quite lame)
Among smaller subjects: