lib/ronin/formatting/extensions/text/string.rb in ronin-0.2.2 vs lib/ronin/formatting/extensions/text/string.rb in ronin-0.2.3
- old
+ new
@@ -24,56 +24,48 @@
require 'chars'
class String
#
- # Creates a new String by passing each character to the specified _block_
+ # Creates a new String by passing each byte to the specified _block_
# using the given _options_.
#
# _options_ may include the following keys:
# <tt>:included</tt>:: The set of characters that will be formated,
# defaults to <tt>Chars.all</tt>.
# <tt>:excluded</tt>:: The characters not to format.
#
- def format_chars(options={},&block)
+ def format_bytes(options={},&block)
included = (options[:included] || Chars.all)
excluded = (options[:excluded] || [])
targeted = included - excluded
formatted = ''
self.each_byte do |b|
- c = b.chr
-
if targeted.include_byte?(b)
- formatted << block.call(c)
+ formatted << block.call(b)
else
- formatted << c
+ formatted << b
end
end
return formatted
end
#
- # Creates a new String by passing each byte to the specified _block_
+ # Creates a new String by passing each character to the specified _block_
# using the given _options_.
#
# _options_ may include the following keys:
# <tt>:included</tt>:: The set of characters that will be formated,
# defaults to <tt>Chars.all</tt>.
# <tt>:excluded</tt>:: The characters not to format.
#
- def format_bytes(options={},&block)
- format_chars(options) do |c|
- i = block.call(c[0])
-
- if i.kind_of?(Integer)
- i.chr
- else
- i.to_s
- end
+ def format_chars(options={},&block)
+ format_bytes(options) do |b|
+ block.call(b.chr)
end
end
#
# Creates a new String by randomizing the case of each character using
@@ -81,21 +73,47 @@
#
# _options_ may include the following keys:
# <tt>:probability</tt>:: The probability that a character will have it's
# case changed; defaults to 0.5.
#
- # "get out your checkbook".rand_case
- # # => "gEt Out YOur CHEckbook"
+ # "get out your checkbook".random_case
+ # # => "gEt Out YOur CHEckbook"
#
def random_case(options={})
prob = (options[:probability] || 0.5)
format_chars(options) do |c|
- if rand < prob
+ if rand <= prob
c.swapcase
else
c
end
end
+ end
+
+ #
+ # Pads the string using the specified _padding_ out to the given
+ # _max_length_. _max_length_ will default to the strings own length,
+ # if not given.
+ #
+ # "hello".pad('A',50)
+ # # => "helloAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ #
+ def pad(padding,max_length=self.length)
+ padding = padding.to_s
+
+ if max_length >= self.length
+ max_length -= self.length
+ else
+ max_length = 0
+ end
+
+ padded = self + (padding * (max_length / padding.length))
+
+ unless (remaining = max_length % padding.length) == 0
+ padded += padding[0...remaining]
+ end
+
+ return padded
end
end