Ruby中arr.partition(&a.method('>'))用法及非元编程实现咨询
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 variablea(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 thatpartitioncan execute. Whenpartitionruns, it passes each element ofarrto this method—so it's effectively running13 > elementfor 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

