| name | ruby-standard-library |
| user-invocable | false |
| description | Use when working with Ruby's standard library including Enumerable, File I/O, Time/Date, Regular Expressions, and core classes. |
| allowed-tools | ["Bash","Read","Write","Edit"] |
Ruby Standard Library
Master Ruby's rich standard library. Ruby comes with powerful built-in classes and modules that handle common programming tasks elegantly.
Enumerable
The Enumerable module provides iteration methods for collections.
Common Enumerable Methods
numbers = [1, 2, 3, 4, 5]
numbers.map { |n| n * 2 }
numbers.map(&:to_s)
numbers.select { |n| n.even? }
numbers.filter(&:odd?)
numbers.reject { |n| n.even? }
numbers.find { |n| n > 3 }
numbers.find_all { |n| n > 2 }
numbers.reduce(0) { |sum, n| sum + n }
numbers.reduce(:+)
numbers.reduce(:*)
numbers.each { |n| puts n }
numbers.each_with_index { |n, i| puts "#{i}: #{n}" }
numbers.each_with_object({}) { |n, hash| hash[n] = n * 2 }
numbers.any? { |n| n > 4 }
numbers.any?(&:even?)
numbers.all? { |n| n > 0 }
numbers.all?(&:even?)
numbers.none? { |n| n < 0 }
numbers.one? { |n| n == 3 }
evens, odds = numbers.partition(&:even?)
numbers.group_by { |n| n % 2 == 0 ? :even : :odd }
[1, 2, 2, 3, 3, 3, 4].chunk(&:itself).to_a
numbers.take(3)
numbers.drop(3)
numbers.take_while { |n| n < 4 }
numbers.drop_while { |n| n < 4 }
[1, 2, 3].zip(['a', 'b', 'c'])
numbers.min
numbers.max
numbers.minmax
[3, 1, 4, 1, 5].sort
['cat', 'dog', 'bird'].sort_by(&:length)
[1, 2, 2, 3, 3, 3].uniq
[1, nil, 2, nil, 3].compact
[[1, 2], [3, 4]].flat_map { |arr| arr.map { |n| n * 2 } }
['a', 'b', 'a', 'c', 'b', 'a'].tally
Arrays
arr = [1, 2, 3]
arr = Array.new(3, 0)
arr = Array.new(3) { |i| i * 2 }
arr[0]
arr[-1]
arr[1..3]
arr.first
arr.last
arr.at(1)
arr << 4
arr.push(5)
arr.unshift(0)
arr.pop
arr.shift
arr.delete_at(1)
arr.delete(3)
arr.insert(1, 'a')
[1, 2] + [3, 4]
[1, 2] * 2
[1, , ] - []
[, ] & [, ]
[, ] |
Hashes
hash = { name: 'Alice', age: 30 }
hash = Hash.new(0)
hash = Hash.new { |h, k| h[k] = [] }
hash[:name]
hash.fetch(:age)
hash.fetch(:email, 'N/A')
hash.dig(:person, :name)
hash[:email] = 'alice@example.com'
hash.delete(:age)
hash.merge!(other_hash)
hash.transform_keys(&:to_s)
hash.transform_values { |v| v.to_s }
hash.each { |key, value| puts "#{key}: #{value}" }
hash.each_key { |key| puts key }
hash.each_value { |value| puts value }
hash.key?(:name)
hash.value?('Alice')
hash.empty?
hash.size
hash.keys
hash.values
hash.invert
hash.select { |k, v| v.is_a?(String) }
hash.reject { || v.? }
hash.compact
hash.slice(, )
Strings
str = "Hello, World!"
str.upcase
str.downcase
str.capitalize
str.swapcase
str.titleize
" hello ".strip
" hello ".lstrip
" hello ".rstrip
str.include?("World")
str.start_with?("Hello")
str.end_with?("!")
str.index("World")
str.rindex("o")
"a,b,c".split(",")
["a", "b", "c"].join("-")
str.sub("World", "Ruby")
str.gsub("o", "0")
str.delete("l")
str.tr("aeiou", "12345")
str[0]
str[..]
str[..]
str.slice(, )
str.empty?
str.length
str.size
str.count()
.to_i
.to_f
.to_s
str.encoding
str.force_encoding()
str.encode()
text =
Regular Expressions
regex = /pattern/
regex = Regexp.new("pattern")
"hello" =~ /ll/
"hello" !~ /zz/
"hello".match(/l+/)
"hello".match?(/l+/)
match = "hello123".match(/(\w+)(\d+)/)
match[0]
match[1]
match[2]
match = "hello123".match(/(?<word>\w+)(?<num>\d+)/)
match[:word]
match[:num]
"hello world".scan(/\w+/)
"a1b2c3".scan(/\d/)
"hello".sub(/l/, 'L')
"hello".gsub(/l/, 'L')
"a:b:c".split()
/pattern/i
/pattern/m
/pattern/x
/\d+\w+\s+^start/
/
/[aeiou]/
/[^aeiou]/
/(cat|
File I/O
content = File.read("file.txt")
lines = File.readlines("file.txt")
File.open("file.txt", "r") do |file|
file.each_line do |line|
puts line
end
end
File.write("file.txt", "content")
File.open("file.txt", "w") do |file|
file.puts "line 1"
file.puts "line 2"
end
File.open("file.txt", "a") do |file|
file.puts "appended line"
end
File.exist?("file.txt")
File.file?("file.txt")
File.directory?("dir")
.size()
.mtime()
.basename()
.dirname()
.extname()
.join(, , )
.entries()
.glob()
.glob()
.mkdir()
.rmdir()
.pwd
.chdir()
.mkdir_p()
.rm_rf()
.cp(, )
.mv(, )
Time and Date
require 'time'
require 'date'
now = Time.now
utc = Time.now.utc
local = Time.now.localtime
now.year
now.month
now.day
now.hour
now.min
now.sec
now.wday
Time.new(2024, 11, 25, 14, 30, 45)
Time.parse("2024-11-25 14:30:45")
Time.at(1700000000)
now.strftime("%Y-%m-%d %H:%M:%S")
now.strftime("%B %d, %Y")
now.iso8601
now + 3600
now - 86400
time2 - time1
date = Date.today
date = Date.new(2024, 11, 25)
date = Date.parse("2024-11-25")
date.year
date.month
date.day
date.wday
date +
date -
date.next_day
date.prev_day
date.next_month
date.prev_year
dt = .now
dt = .parse()
Range
(1..5).to_a
(1...5).to_a
(1..10).include?(5)
(1..10).cover?(5)
(1..10).member?(5)
(1..5).each { |n| puts n }
(1..5).map { |n| n * 2 }
('a'..'e').to_a
case age
when 0..12
"child"
when 13..19
"teen"
else
"adult"
end
Set
require 'set'
set = Set.new([1, 2, 3])
set = Set[1, 2, 3]
set.add(4)
set << 5
set.delete(3)
set1 | set2 # Union
set1 & set2 # Intersection
set1 - set2 # Difference
set1 ^ set2 # Symmetric difference
# Query
set.include?(2) # true
set.empty? # false
set.size # 3
# Subset/superset
set1.subset?(set2)
set1.superset?(set2)
Best Practices
- Use Enumerable methods instead of manual loops
- Chain methods for readability:
array.select(&:even?).map(&:to_s)
- Use symbol-to-proc (
&:method_name) when possible
- Prefer File.open with blocks for automatic file closing
- Use
fetch for hashes when you want to handle missing keys
- Leverage lazy enumerables for large collections
- Use
Pathname for complex path operations
Anti-Patterns
❌ Don't use for loops - use Enumerable methods
❌ Don't forget to close files - use blocks with File.open
❌ Don't use each for transformation - use map
❌ Don't use each for filtering - use select or reject
❌ Don't mutate arrays while iterating - use methods that return new arrays
Related Skills
- ruby-oop - For understanding core classes
- ruby-blocks-procs-lambdas - For working with Enumerable
- ruby-metaprogramming - For advanced library usage