Saltar al contenido
Skillpedia
Programación general48 mil · #5897

ruby

Qué hace

Esta guía ayuda a los programadores de Ruby a escribir código más limpio y eficiente. Muestra cómo usar las herramientas integradas del lenguaje para hacer tareas de forma más sencilla y rápida.

Cuándo usarla

  • ✓Cuando quieres que tu código Ruby sea más fácil de leer.
  • ✓Cuando aprendes buenas prácticas para escribir Ruby.
  • ✓Para optimizar el rendimiento de tu código Ruby.

Link de la skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/ruby/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/ruby/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo escribir código Ruby más idiomático para agrupar elementos?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

La IA compara ejemplos de código 'malo' con ejemplos 'buenos' en Ruby. Te sugiere usar métodos específicos del lenguaje que resuelven el problema de forma más concisa y eficiente.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de 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

  1. Enumerable & Collections
  2. Blocks, Procs & Lambdas
  3. String Handling
  4. Error Handling
  5. Classes & Modules
  6. Ruby Idioms
  7. 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

…
Preguntas frecuentes

¿Qué significa 'idiomático' en programación?

Significa escribir código que sigue las convenciones y el estilo que la comunidad de programadores espera para un lenguaje concreto, haciéndolo más natural y fácil de entender para otros.

¿Por qué es importante usar métodos como `map` y `select` en lugar de bucles manuales?

Estos métodos suelen ser más cortos, más legibles y menos propensos a errores que escribir bucles a mano. Además, pueden ser más eficientes.

¿Qué son los 'anti-patrones'?

Son enfoques de programación habituales que parecen funcionar, pero que en realidad generan código más complejo, más difícil de mantener o ineficiente. La guía muestra cómo evitarlos.

Detalles

Descripción original del autor

Language-specific super-code guidelines for ruby.

repo: sickn33/agentic-awesome-skills

Popularidad

Estrellas en GitHub
48 mil
Posición en el ranking
#5897
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas