File: shadow.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (37 lines) | stat: -rw-r--r-- 639 bytes parent folder | download
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 Symbol

  # Easily manipulate undercores on symbols.
  #
  #   :a.pad(2)         #=> :__a__
  #   :__a__.pad(-1)    #=> :_a_
  #
  #   CREDIT: Trans

  def shadow(i=1)
    return self if i == 0
    s = self.to_s
    if i > 0
      return ( ('_'*i) + self.to_s + ('_'*i) ).to_sym
    else
      i *= -1
      return s[i..-i-1].to_sym if s[0..i-1] == ('_'*i) and s[-i..-1] == ('_'*i)
      return self
    end
  end
  alias :pad :shadow

end

__END__

require 'test/unit'

class TestSymbolShadow < Test::Unit::TestCase

  def test_shadow
    assert_equal( :__a__, :a.shadow(2) )
    assert_equal( :_a_, :__a__.shadow(-1) )
  end

end