Leon's Blogging

Coding blogging for hackers.

Ruby - Unary Operator

| Comments

In Ruby, a unary operator is an operator which only takes a single ‘argument’ in the form of a receiver.

unary operator likes + - ! ~ & *..

1
2
3
4
5
6
7
8
9
10
-8
# => -8

# 2.2.3 Ruby
-'test'
# NoMethodError: private method `-@' called for "test":String

# 2.4.1 之後似乎就不會有 error
-'test'
# => "test"

Add -@ method to String class

1
2
3
4
5
6
7
8
9
class String
  def -@
     self + " hello"
    end
end
# => :-@

-'test'
# => "test hello"

Full Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class MagicString < String
  def +@
    upcase
  end

  def -@
    downcase
  end

  def ~
    # Do a ROT13 transformation - http://en.wikipedia.org/wiki/ROT13
    tr 'A-Za-z', 'N-ZA-Mn-za-m'
  end

  def to_proc
    Proc.new { self + " hello" }
  end

  def to_a
    [self.reverse]
  end

 def !
   swapcase
 end
end

str = MagicString.new("This is my string!")
p +str                   # => "THIS IS MY STRING!"
p ~str                   # => "Guvf vf zl fgevat!"
p +~str                  # => "GUVF VF ZL FGEVAT!"
p %w(a b).map(&str)      # => ["This is my string! hello", "This is my string! hello"]
p *str                   # => "!gnirts ym si sihT"

p !str                   # => "tHIS IS MY STRING!"
p (not str)              # => "tHIS IS MY STRING!"
p !(~str)                # => "gUVF VF ZL FGEVAT!"

Reference

Comments