Project

General

Profile

Feature #4475

default variable name for parameter

Added by jordi (jordi polo) about 7 years ago. Updated about 1 month ago.

Status:
Assigned
Priority:
Normal
Target version:
-
[ruby-core:<unknown>]

Description

=begin

There is a very common pattern in Ruby:

object.method do |variable_name|
variable_name doing something

end

Many times in fact the name of the object is so self explanatory that we don't care about the name of the variable of the block. It is common to see things like :

@my_sons.each { |s| s.sell_to_someone }

or

Account.all.each { |a| my_account << a.money }

People tend to choose s or a because we have the class or the object name just there to remind you about the context.

I would like to know if can be a good idea to have a default name for that parameter. I think it is Groovy that does something like:

Account.all.each { my_account << it.money }

Where it is automagically filled and it doesn't need to be declared.

I think it is as readable or more (for newbies who don't know what is ||) and we save some typing :)

=end

History

#1 Updated by wardrop (Tom Wardrop) about 7 years ago

=begin
I like the suggestion. The magic variable I'd use for this pattern would be 'this'. For example:

posts.each { this.author = 'Santa Clause' }

The rule would be: The first argument of any block would be accessible from within the block through the special variable 'this'.
=end

#2 [ruby-core:43439] Updated by nahi (Hiroshi Nakamura) about 6 years ago

  • Description updated (diff)
  • Category set to core
  • Status changed from Open to Assigned
  • Assignee set to matz (Yukihiro Matsumoto)

#3 [ruby-core:49705] Updated by mame (Yusuke Endoh) over 5 years ago

  • Target version set to 2.6

#4 Updated by naruse (Yui NARUSE) 5 months ago

  • Target version deleted (2.6)

#5 [ruby-core:86598] Updated by knu (Akinori MUSHA) about 1 month ago

I would like the feature, but we have many things to think about.

We would not be able to make "it" a reserved keyword because that would destroy all existing RSpec code written in tens of thousands of projects.

If "it" were to be implemented as a method, how could we make it work inside of a BasicObject instance? What if a method of the same name was defined?

If "it" were to be implemented as a local variable, should its name be included in local_variables?

All things considered, I guess the variable name would have to be $-something, if any.

#6 [ruby-core:86607] Updated by matz (Yukihiro Matsumoto) about 1 month ago

This is a very interesting idea but at the same time, it's difficult to keep compatibility.
At least simple addition of it does not work well.

Matz.

Also available in: Atom PDF