Project

General

Profile

Feature #15286

Proposal: Add Kernel.#expand(*args)

Added by osyo (manga osyo) 14 days ago. Updated 1 day ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:89737]

Description

This is a suggestion for Hash shorthand.

Kernel.#expand(*args) is expand local variable and method to Hash.
*args is method or local variable names.

Example

def meth
  "meth"
end
a, b, c = 1, 2, 3

# #expand args is local variable or method names
# Expand to { a: a, b: b: meth: meth }
p expand(:a, :b, :meth)
# => {:a=>1, :b=>2, :meth=>"meth"}

# Error: `expand': undefined method `hoge' for main:Object (NoMethodError)
p expand(:hoge)

What can be expanded,

  • local variable
  • method

and, If there are duplicate names, prioritize local variable.

def meth
   "meth"
end
meth = 42

p expand(:meth)
# => {:meth=>42}

pull request: https://github.com/ruby/ruby/pull/2006

History

#1 [ruby-core:89739] Updated by shevegen (Robert A. Heiler) 14 days ago

I think one possible question in regards to the suggestion here is whether the above method may be useful
on its own, even without a shorthand syntax for Hash. (This is really just a question; I personally am
not having any strong pro/con opinion.)

I also understand that using a method is different compared to the other two proposals. For example,

{ a }
{ a: a}

and

{x, y}
{x: x, y: y}

is different to:

meth = 42
p expand(:meth) # => {:meth=>42}

So using a method is different to the other two proposals (in the two older
issue request, by Ignatius and Shugo Maeda). Perhaps one or more use cases
could be described for a new method to be useful even without the hash
shorthand notation? I can not think of a good one right now but perhaps others
have some ideas.

#2 [ruby-core:89741] Updated by osyo (manga osyo) 14 days ago

Thanks for comment, shevegen.
Kernel.#expand can be used as follows.

names = [:a, :b, :meth]

# expand(:a, :b, :meth)
expand(*names)
# => {:a=>1, :b=>2, :meth=>"meth"}

# ???
{ *names }

#3 [ruby-core:89861] Updated by nobu (Nobuyoshi Nakada) 1 day ago

Interesting feature, but I don't think the name Kernel#expand is acceptable.
Maybe an instance method of Binding?
And I think it should raise a NameError instead of a NoMethodError on invalid names.

#4 [ruby-core:89863] Updated by nobu (Nobuyoshi Nakada) 1 day ago

And, what do you expect for keywords, e.g., __FILE__, __LINE__, self, super, and etc?

Also available in: Atom PDF