Feature #13207


Allow keyword local variable names like `class` or `for`

Added by kaspth (Kasper Timm Hansen) over 5 years ago. Updated over 5 years ago.

Target version:


Sometimes when trying to write expressive Ruby you enevitably hit a case
that would sound just right if the variable name matches a Ruby keyword.

E.g. writing a method to output HTML tags:

def label_tag(text, class:)
  %(<label class=""#{class.camelize}>#{text}</label>")

Or a method to generate a representation for a specific purpose:

def to_gid(for:)
  for ||= :universal
  GlobalID.generate(, id, for)

Currently Ruby's keywords get in the way of the type of code we'd like to write.
Instead we have to use variable names like klass or modjule:

[ A::B, C::D ].each { |klass| puts }

It would make me a happier programmer if I could write more naturally instead of
worrying about keywords clashing with local variable names.

It also stands to me that far more often when there is a potential clash I want
the variable name to win out. It's unlikely I will be defining classes or
modules within a method say. In those rare cases where I do,
we could expose keywords like this: Keyword.class, Keyword.for etc.

I propose that renaming a keyword is fair game anywhere except the root scope and
that a rename follows local variable scoping.

NOTE: I think this could also remove the self currently needing to be
prepended to self.class.

I hope this can be yet another case in Ruby's quest to go a bit out of its way
to make programmers lives happier. Thanks!

Related issues 1 (1 open0 closed)

Related to Ruby master - Feature #17785: Allow named parameters to be keywordsOpenmatz (Yukihiro Matsumoto)Actions

Also available in: Atom PDF