Skip to content

Instantly share code, notes, and snippets.

@lnznt
Last active October 3, 2015 19:48
Show Gist options
  • Save lnznt/2515488 to your computer and use it in GitHub Desktop.
Save lnznt/2515488 to your computer and use it in GitHub Desktop.
String#remove / String#- (Ruby)
#!/usr/bin/env ruby
module StringEx
def remove(re)
gsub(re) {}
end
def wrap(w)
"#{w[0]}#{self}#{w[-1]}"
end
def indent(n, s=' ')
"#{s * n}#{self}"
end
alias - remove
alias ** wrap
alias >> indent
end
if __FILE__ == $0
class String
include StringEx
end
p "AB-C-AB" - "AB" # => "-C-"
p "AB-C-AB" - "C-AB" # => "AB-"
p "AB-BB-AB" - /^AB/ # => "-BB-AB"
p "AB-BB-AB" - /AB$/ # => "AB-BB-"
p "AB-BB-AB" - /AB/ # => "-BB-"
p "hello" ** "()" # => "(hello)"
p "hello" ** "|" # => "|hello|"
p "hello" ** "{...}" # => "{hello}"
p "hello" ** "->" # => "-hello>"
p "hello" ** ['(',')'] # => "(hello)"
p "hello" ** ['|'] # => "|hello|"
p "hello" ** ['{',nil,'}'] # => "{hello}"
p "hello" ** ['-','>'] # => "-hello>"
red = ["\e[31m", "\e[m"]
p "hello" ** red # => "\e[31mhello\e[m"
p "hello" >> 2 # => " hello"
p "hello".indent 2, ">" # => ">>hello"
p "hello".indent 2, "->" # => "->->hello"
end
# vi:set ts=2 sw=2 et:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment