1evaluates to an instance ofInt1.0evaluates to an instance ofFloat"foo"evaluates to an instance ofStringtrueandfalseevaluates to an instance ofBool
[1, 2]evaluates to an instance ofArray<Int>[1, "foo"]evaluates to an instance ofArray<Object>
Example
class A
def foo
self #=> The type of `self` is `A` here
self.bar
end
def bar
puts "bar"
end
end
In the toplevel, self evaluates to the toplevel self. The type of toplevel self is Object.
There are two ways to declare a local variable.
let x = 1var x = 1
Reassigning to x only allowed for the latter form.
let @a = 1var @a = 1
An instance of the classes Fn0, Fn1, ..., Fn9 is called a lambda. Lambdas can be created by lambda expression.
fn{ p 1 }evaluates to an instance ofFn0<Void>fn(x: Int){ p x }evaluates to an instance ofFn1<Int, Void>
f = fn{ p 1 }
f()
f must be an instance of Fn.
1.absfoofoo()foo(1, 2, 3)
foo(1, 2, 3){|x: Int| p x}foo(1, 2, 3) do |x: Int| p x end
These are mostly equal to
foo(1, 2, 3, fn(x: Int){ p x })
but some behaviors, break and return for example, are different between fn (a lambda made by lambda expression) and block (a lambda made by {} or do...end on a method call).
The type of these expressions are Bool.
!xx and yx or y
Example
if foo
puts "foo"
elsif bar
puts "bar
else
puts "otherwise"
end
x = if a then b else c end
The type of an if condition (foo, bar and a avobe) must be Bool.
else-less if, for example
if foo
puts "foo"
end
is equivalent to
if foo
puts "foo"
else
Void
end
Neverif all branches have typeNever. Otherwise:Voidif a branch has typeVoid. Otherwise:- If all the branches have either type
Neveror type A, A. Otherwise thisifis invalid (compile-time error.)
x if y is equivalent to
if x
y
end
unless foo
puts "otherwise"
end
is equivalent to
if !foo
puts "otherwise"
end
Note: unless cannot take elsif or else clause.
x unless y is equivalent to
if !x
y
end
a ? b : c is equivalent to
if a
b
else
c
end
var a = 1
while a < 10
p a
a += 1
end
Type of a while expressions is Void.
- Find the nearest
while/fn/block - If the found one is
while, escape from thewhile - If the found one is fn, compile-time error
- If the found one is block, escape from the method that given the block
- If none found, compile-time error
Example
[1, 2, 3].each do |i: Int|
p i
break if i == 2 #=> escapes from `each`
end
Type of a break expressions is Never.
- Find the nearest fn/method
- If the found one is fn, escape from the fn
- If the found one is method, escape from the method
- If none found, compile-time error
Type of a return expressions is Never.
(NOTE: non-local return is not yet implemented - see #242)