Last active
January 21, 2022 00:05
-
-
Save rewinfrey/df38c777a561b1dcce68d8db1cd75992 to your computer and use it in GitHub Desktop.
Shows examples of Ruby 3.1's new hash value omission syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Hash value omission in Ruby 3.1: https://bugs.ruby-lang.org/issues/14579 | |
x = 1 | |
y = 2 | |
a = {x:, y:} | |
p a # => {:x=>1, :y=>2} | |
module XY | |
def x; 10; end | |
def y; 20; end | |
end | |
self.class.include XY | |
# In this scope, x and y are not referenced via `self`, so still retain their initial values. | |
p x # => 1 | |
p y # => 2 | |
# Here, x and y are referenced via `self`, so the values used are those bound by the included XY module on line 13. | |
p self.x # => 10 | |
p self.y # => 20 | |
def method_example(x:, y:) | |
# x and y are originally bound to the method's input arguments, which are defined based on what is reachable in the caller's scope. | |
p x # => 1 | |
p y # => 2 | |
# x and y are redefined and hash value ommission uses these new values below. | |
x = 100 | |
y = 200 | |
{x:, y:} | |
end | |
c = method_example(x:, y:) | |
p c # => {:x=>100, :y=>200} | |
class Example | |
include XY | |
attr_accessor :h | |
def initialize(x:, y:) | |
# Similarly to the method example, x and y are defined according to the | |
# input arguments to the constructor based on what is reachable in the caller's scope. | |
@h = {x:, y:} | |
end | |
def reset_h | |
# In this scope, the x and y in scope come from the included XY module, | |
# and overwrites the previously set x and y values in the constructor. | |
@h = {x:, y:} | |
end | |
end | |
def class_example(x:, y:) | |
Example.new(x:, y:) | |
end | |
d = class_example(x:, y:) | |
p d # => #<Example:0x0000000106dd00c0 @h={:x=>1, :y=>2}> | |
d.reset_h | |
p d # => <Example:0x000000010539e9e0 @h={:x=>10, :y=>20}> | |
# not valid: | |
# z = {"x" =>, "y" =>} | |
# not valid: | |
# z = {x, y} | |
# not valid: | |
# z = { "x:", "y:" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment