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

Ruby中arr.partition(&a.method('>'))用法及非元编程实现咨询

Understanding arr.partition(&a.method('>')) in Ruby

Hey there! Let's break down this Ruby code step by step so it makes total sense.

What Does arr.partition(&a.method('>')) Do?

First, let's recap what Array#partition does: this built-in method splits your array into two new arrays. The first array contains every element where the block you pass returns true, and the second array holds all elements where the block returns false.

Now let's unpack the tricky-looking &a.method('>') part:

  • a.method('>'): In Ruby, operators like > are just methods! This line grabs the method object for the > operator attached to your variable a (which has a value of 13 here). Think of it as a reference to the "greater than" function that belongs to the number 13.
  • The & symbol: This converts the method object into a block that partition can execute. When partition runs, it passes each element of arr to this method—so it's effectively running 13 > element for every item in the array.

Let's tie this to your example code and output:

a = 13
arr = [10, 11, 13, 22]
left, right = arr.partition(&a.method('>'))
p left
p right

Output:

[10, 11]
[13, 22]

The left array has elements where 13 > element is true (10 and 11), and the right array has elements where that comparison is false (13 and 22).

Implementing the Same Logic Without Metaprogramming

Using a.method('>') counts as metaprogramming because you're dynamically grabbing a method object instead of writing the logic directly. If you want to avoid that, the simplest approach is to write the comparison explicitly in a block—this is also more readable for most developers.

Here's the equivalent code:

a = 13
arr = [10, 11, 13, 22]
left, right = arr.partition { |num| a > num }
p left  # => [10, 11]
p right # => [13, 22]

This does exactly the same thing as the original code—we're just directly defining the block logic instead of dynamically fetching the > method.

If you need to reuse this comparison logic elsewhere, you can also use a lambda (a reusable block) instead:

a = 13
arr = [10, 11, 13, 22]
greater_than_a = ->(num) { a > num }
left, right = arr.partition(&greater_than_a)
p left  # => [10, 11]
p right # => [13, 22]

But for one-off use cases, the simple inline block is usually the best choice.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:27:58