Những method tiện tay cho IRB

Dưới đây là một đống snippets để nhét vào IRB config để scripting cho tiện, hoặc dùng cho mục đích cá nhân. Đừng nhét trực tiếp đống này vào bất cứ codebase nào.

Set XOR

class Array
  # Returns the union of `array` and Array `other` minus elements in both.
  def ^(other)
    (self | other) - (self & other)
  end
end

Random

class Random
  # Return a random boolean value.
  def self.bool
    [true, false].sample
  end

  # Returns a random string containing `size` characters from `characters`.
  def self.string(size, characters = [*'a'..'z', *'A'..'Z', *'0'..'9'])
    Array.new(size) { characters.sample }.join
  end

  # Return a random boolean value.
  def bool
    self.rand(2).zero?
  end

  # Returns a random string containing `size` characters from `characters`.
  def string(size, characters = [*'a'..'z', *'A'..'Z', *'0'..'9'])
    Array.new(size) { characters[self.rand(characters.size)] }.join
  end
end

Nếu bạn muốn tạo string ngẫu nhiên một cách bảo mật, hãy dùng SecureRandom.

Clear

# Clear the terminal.
def clear
  print "\033c"
end

Null stream

$null = File.open(File::NULL, 'w')

<3