ruby
它能做什么
这份指南帮助 Ruby 程序员编写更简洁、更高效的代码。它展示了如何使用语言内置的工具,更简单、更快速地完成任务。
适用场景
- ✓当你希望 Ruby 代码更易读时。
- ✓当你想学习编写 Ruby 代码的最佳实践时。
- ✓当你想优化 Ruby 代码的性能时。
技能链接
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/ruby/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“如何编写更符合 Ruby 习惯(idiomatic)的分组代码?”
每周 5 个新技能,1 分钟读完。
工作原理
AI 会将“不好”的代码示例与“好”的 Ruby 示例进行对比。它会建议使用特定的语言方法,以更简洁、更高效的方式完成任务。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Ruby: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for ruby.
Table of Contents
- Enumerable & Collections
- Blocks, Procs & Lambdas
- String Handling
- Error Handling
- Classes & Modules
- Ruby Idioms
- Anti-patterns specific to Ruby
1. Enumerable & Collections {#enumerable}
# ❌ Manual accumulation
result = []
items.each do |item|
result << item.name.upcase if item.active?
end
# ✅
result = items.select(&:active?).map { |i| i.name.upcase }
# ❌ Manual grouping
grouped = {}
items.each do |item|
grouped[item.category] ||= []
grouped[item.category] << item
end
# ✅
grouped = items.group_by(&:category)
# ❌ Manual sum
total = 0
orders.each { |o| total += o.amount }
# ✅
total = orders.sum(&:amount)
# ❌ Checking existence then accessing
if hash.key?(key)
value = hash[key]
end
# ✅
value = hash[key] # returns nil if missing
# or with default:
value = hash.fetch(key, default_value)
# or raising on missing:
value = hash.fetch(key) # raises KeyError
Prefer map/select/reject/sum over manual loops. Use &:method for single-method blocks.
2. Blocks, Procs & Lambdas {#blocks}
# ❌ Explicit block-to-proc conversion when unnecessary
items.map { |item| item.to_s }
# ✅
items.map(&:to_s)
# ❌ Proc.new when lambda is safer (arity check + return behavior)
handler = Proc.new { |x| x * 2 }
# ✅
handler = ->(x) { x * 2 }
# ❌ Multi-line block with { }
items.map { |item|
result = transform(item)
validate(result)
result
}
# ✅ — do/end for multi-line, { } for single-line
items.map do |item|
result = transform(item)
validate(result)
result
end
3. String Handling {#strings}
# ❌ String concatenation in loop
result = ""
items.each { |i| result += i.name + ", " }
# ✅
result = items.map(&:name).join(", ")
# ❌ String concatenation for assembly
greeting = "Hello, " + name + "! You have " + count.to_s + " messages."
# ✅
greeting = "Hello, #{name}! You have #{count} messages."
# ❌ Mutable string where frozen is fine (Ruby 3+ encourages frozen)
SEPARATOR = ", "
# ✅
SEPARATOR = ", ".freeze
# or add `# frozen_string_literal: true` at file top
Use heredocs (<<~HEREDOC) for multi-line strings. <<~ strips indentation.
4. Error Handling {#errors}
# ❌ Rescuing Exception (catches EVERYTHING including SignalException, SystemExit)
begin
risky
rescue Exception => e
log(e)
end
# ✅ — rescue StandardError (the default)
begin
risky
rescue StandardError => e
log(e)
raise
end
# or just: rescue => e (same as StandardError)
# ❌ Using rescue as flow control
begin
value = hash.fetch(key)
rescue KeyError
value = default
end
# ✅
value = hash.fetch(key, default)
# ❌ Inline rescue hiding errors
result = dangerous_operation rescue nil
# ✅ — inline rescue only for truly trivial fallbacks
result = Integer(input) rescue nil # acceptable for parsing
5. Classes & Modules {#classes}
# ❌ Manual accessors
class User
def name
@name
end
def name=(value)
@name = value
end
end
# ✅
class User
attr_accessor :name
end
# ❌ Deep inheritance for shared behavior
class Animal; end
class Pet < Animal; end
class Dog < Pet; end
# ✅ — mixins for shared behavior, inheritance for "is-a"
module Trainable
def train = puts("Training #{name}")
end
class Dog
include Trainable
attr_reader :name
def initialize(name) = @name = name
end
# ❌ Class with only class methods (namespace via class)
class MathUtils
def self.square(x) = x * x
def self.cube(x) = x ** 3
end
# ✅
module MathUtils
module_function
def square(x) = x * x
def cube(x) = x ** 3
end
6. Ruby Idioms {#idioms}
# ❌ Explicit boolean return
def active?
if status == :active
true
else
false
end
end
# ✅
def active? = status == :active
# ❌ nil check before method call
if user && user.name
puts user.name
end
# ✅ (Ruby 2.3+)
puts user&.name if user&.name
# or with safe navigation:
user&.name&.then { |n| puts n }
# ❌ Conditional assignment verbosely
if @cache.nil?
@cache = expensive_compute
end
# ✅
@cache ||= expensive_compute
…
常见问题
“idiomatic”在编程中是什么意思?
它指编写符合某种编程语言社区约定和风格的代码。这样代码读起来更自然,也更便于其他人理解。
为什么要使用 `map`、`select` 等方法,而不是手写循环?
这些方法通常比手写循环更短、更易读,也更不容易出错,有时还更高效。
什么是“反模式”(anti-patterns)?
它们是一些看似可行、实际上会让代码更复杂、更难维护或效率更低的常见写法。指南会告诉你如何避免它们。
详情
热度
- GitHub 星标
- 48k
- 排名
- #5897
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。