Unary operators and splats

Binary operator
1 + 3
=> 4
class Fixnum
def +(other)
self - other
end
end
1 + 3
=> -2
Unary operator
-1
=> -1
-(-1)
=> 1
+1
=> 1
!true
=> false
Unary operator
class String
def -@
downcase
end
def +@
upcase
end
end
- "aAaA"
+ "aAaA"
! and ~
class Foo
def !
# something
end # same as not
def ~
# something
end
end
&
['hello', 'world'].map { |x| x.reverse }
=> ["olleh", "dlrow"]
['hello', 'world'].map(&:reverse)
=> ["olleh", "dlrow"]
:reverse.to_proc.call(['hello', 'world'])
=> ["olleh", "dlrow"]
class Symbol
def to_proc
end
end
*
a = *1..10
puts a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
class Range
def to_a
end
end
* sugar
def say(what, *people)
people.each{ |person| puts "#{person}: #{what}" }
end
say "Hello", "Alice", "Bob", "Eve"
=> Alice: Hello
=> Bob: Hello
=> Eve: Hello
* sugar
def say(what, *people, salute)
people.each{ |person| puts "#{person}: #{what}, #{salute}!" }
end
say("Bye", "Alive", "Bob", "Eve", "See you later")
=> Alive: Bye, See you later!
=> Bob: Bye, See you later!
=> Eve: Bye, See you later!
* sugar
def arguments_and_opts(*args, opts)
puts "arguments: #{args} options: #{opts}"
end
arguments_and_opts(1,2,3, a: 5, b:6)
=> arguments: [1, 2, 3] options: {:a=>5, :b=>6}
* sugar
letters = ["a", "b", "c", "d", "e"]
first, second = letters
puts "#{first}, #{second}"
=> "a", "b"
first, *second = letters
puts "#{first}, #{second}"
=> "a", ["b", "c", "d", "e"]
first, *center, last = letters
puts "#{first}, #{center}, #{last}"
=> "a", ["b", "c", "d"], "e"
* sugar
some_numbers = [1, 2, 3]
up_to_five = [some_numbers, 4, 5]
puts up_to_five
=> [[1, 2, 3], 4, 5]
up_to_five = [*some_numbers, 4, 5]
puts up_to_five
=> [1, 2, 3, 4, 5]
testrocket gem
require 'testrocket'
# BASIC USAGE
# +-> { block that should succeed }
# --> { block that should fail }
+-> { Die.new(2) }
--> { raise }
+-> { 2 + 2 == 4 }
https://github.com/peterc/testrocket
operators
By Jan Varljen
operators
- 598