You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化Ruby中数字映射姓名的长case赋值语句?

Optimizing That Long Ruby Case Statement

Great question! That sprawling case statement is definitely ripe for cleanup—Ruby gives us a couple of neat, concise ways to handle this kind of integer-to-string mapping. Here are the best approaches depending on your use case:

1. Use an Array (Best for Consecutive Integer Keys)

Since your keys are consecutive integers from 1 to 30, an array is the most efficient and clean solution. Ruby arrays use 0-based indexing, so we just need to adjust the input value by subtracting 1 to match the array's position:

# Define a constant for the name list (reusable, readable)
NAMES = [
  "Noah", "Liam", "Mason", "Jacob", "William",
  "Ethan", "James", "Alexander", "Michael", "Benjamin",
  "Elijah", "Daniel", "Aiden", "Logan", "Matthew",
  "Lucas", "Jackson", "David", "Oliver", "Jayden",
  "Joseph", "Gabriel", "Samuel", "Carter", "Anthony",
  "John", "Dylan", "Luke", "Henry", "Andrew"
]

# Map the integer to the corresponding name
@name = NAMES[@name - 1]

This cuts down the code drastically and keeps the name list organized. Using a constant (uppercase naming) follows Ruby conventions and lets you reuse this list elsewhere in your code if needed.

2. Use a Hash (Better for Non-Consecutive or Arbitrary Keys)

If you ever expect to add non-consecutive integer keys (or want more explicit key-value pairing), a hash is the way to go. It’s slightly more verbose but makes the mapping crystal clear:

# Define a constant hash for explicit key-value pairs
NAME_MAP = {
  1 => "Noah", 2 => "Liam", 3 => "Mason", 4 => "Jacob", 5 => "William",
  6 => "Ethan", 7 => "James", 8 => "Alexander", 9 => "Michael", 10 => "Benjamin",
  11 => "Elijah", 12 => "Daniel", 13 => "Aiden", 14 => "Logan", 15 => "Matthew",
  16 => "Lucas", 17 => "Jackson", 18 => "David", 19 => "Oliver", 20 => "Jayden",
  21 => "Joseph", 22 => "Gabriel", 23 => "Samuel", 24 => "Carter", 25 => "Anthony",
  26 => "John", 27 => "Dylan", 28 => "Luke", 29 => "Henry", 30 => "Andrew"
}

# Look up the name directly by key
@name = NAME_MAP[@name]

No index adjustment needed here—just a direct lookup. This is also easier to modify if you need to add or remove specific key-value pairs later.

Quick Note on Edge Cases

If @name could be a value outside 1-30, both methods will return nil by default. If you want a fallback value, you can add it like this:

  • For the array approach: @name = NAMES.fetch(@name - 1, "Default Name")
  • For the hash approach: @name = NAME_MAP.fetch(@name, "Default Name")

内容的提问来源于stack exchange,提问作者il mietitore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:20:31