String
Format
sprintf('%02d:%02d',8,5)
#=> 08:05
Rubocop Style/FormatString: Favor format over sprintf
format('%02d:%02d',8,5)
#=> "08:05"
Guarantee length random string
(36**(length-1) + rand(36**length - 36**(length-1))).to_s(36)
Get 8-bit byte from string
"ABC".getbyte(0)
=> 65
"ABC".getbyte(1)
=> 66
"ABC".getbyte(2)
=> 67
A simple encrypter (modified from the example on Design Patterns in Ruby)
class Encrypter
def initialize(key)
@key = key
end
def encrypt(reader, writer)
key_index = 0
while not reader.eof?
clear_char = reader.getc
encrypted_char = clear_char.getbyte(0) ^ @key[key_index].getbyte(0)
writer.putc(encrypted_char)
key_index = (key_index + 1) % @key.size
end
end
end
message = File.open('message.txt', 'w')
message.write('This is plain message')
message.close
encrypter = Encrypter.new('my secret key')
reader = File.open('message.txt')
writer = File.open('message.encrypted.txt', 'w')
encrypter.encrypt(reader, writer)
reader.close
writer.close
decrypter = Encrypter.new('my secret key')
reader = File.open('message.encrypted.txt')
writer = File.open('message.decrypted.txt', 'w')
decrypter.encrypt(reader, writer)
reader.close
writer.close
Multi-line string
ruby 2.0+
%( )
multi_line_string = %(
line 1
line 2
line 3
)
puts multi_line_string
# =>
#
# line 1
# line 2
# line 3
p multi_line_string
# => "\nline 1\nline 2\nline 3\n"
last 4 numbers
"abcdefg".last(4)
# => defg
Convert string to symbol
"This IS A book".parameterize.underscore.to_sym
# => :this_is_a_book
Sub:remove no needed partial string
"http://test.example.com".sub("http://","")
# => "test.example.com"
pluralize
'singular_none'.pluralize(count)
'month'.pluralize(1)
#=> "month"
'month'.pluralize(2)
#=> "months"
Reference
- getbyte
- Ruby Strings
- Ruby does not recognize the “^=” operator
- String
- More On Strings
- sprintf
- How best to generate a random string in Ruby
- Ruby: Can I write multi-line string with no concatenation?
- last
- Format
- Convert string to symbol-able in ruby
- sub
- The Elements of Style in Ruby #2: Favor Sprintf(format) Over String#%
- Kernel
- Ruby Sprintf: An Easy, Versatile Way to Format Strings