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

关于Ruby块中| |之间参数命名规则的技术问询

Ruby Block Parameter Names: Readability vs. Rules

Awesome question—this is a common point of confusion when first diving into Ruby blocks, so let’s unpack it clearly.

First off, let’s get straight to the core answer: Block parameter names are 100% for readability and semantic clarity—Ruby has no hard rules enforcing specific names. You can use |i| for every block if you want, but there are good reasons not to.

Let’s break this down with your examples:

Syntax doesn’t care about names, only order/quantity

Your code examples work because Ruby only pays attention to how many parameters your block accepts, and their order—not what you call them. For example, you could swap the names in your code and it would run exactly the same:

# Array iteration with "line" instead of "i"
[1, 3, 5, 7, 9].each { |line| puts line }

# File line iteration with "i" instead of "line"
f = File.open("testfile")
f.each do |i| puts i end
f.close

This will output the array elements and file lines just like your original code—Ruby doesn’t bat an eye at the parameter names. Even for blocks that take multiple parameters (like Hash#each, which passes key-value pairs), only the order matters: |key, value|, |k, v|, or even |a, b| all work as long as the first parameter captures the key and the second captures the value.

So why do people use different names?

The main reason is readability. When you use a name that describes what the parameter represents, anyone reading your code (including future you!) can immediately understand what’s happening without extra mental work.

For example:

  • Using |line| when iterating over a file makes it obvious you’re dealing with individual lines of text.
  • Using |user| when iterating over a list of user objects tells you exactly what each element is.
  • Using generic names like |i| works for simple one-off loops, but becomes confusing in more complex code—especially with nested blocks:
    # Hard to follow: what does each "i" represent?
    [["apple", 2], ["banana", 5]].each do |i|
      i.each do |i|
        puts i
      end
    end
    
    # Clearer at a glance:
    [["apple", 2], ["banana", 5]].each do |fruit_pair|
      fruit_pair.each do |item|
        puts item
      end
    end
    

Generic names can also lead to variable shadowing (reusing the same name for different variables in nested scopes), which can introduce bugs that are hard to track down.

Final takeaway

  • Technically: You can use any parameter name you want—Ruby won’t enforce anything here.
  • Practically: Use semantic, descriptive names to make your code self-documenting. It’s a small habit that makes a huge difference for maintainability.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:42:40