Created
May 8, 2019 12:15
-
-
Save naohaq/b3013672934576cbf495e5209578c36d to your computer and use it in GitHub Desktop.
Sophisticated semantics of Ruby
This file contains 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
class Hoge | |
def a=(x) | |
puts "Pooh!" | |
end | |
private "a=".intern | |
def a | |
puts "Bra!" | |
end | |
private :a | |
def m0 | |
self.a = 100 | |
end | |
def m1 | |
p a | |
end | |
def m2 | |
p self.a | |
end | |
end | |
class Foo | |
def m1 | |
p a | |
end | |
end | |
x = Hoge.new | |
begin | |
puts "-- Calling Hoge#m0" | |
x.m0 | |
rescue => e | |
printf "> %s\n", e.inspect | |
end | |
begin | |
puts "-- Calling Hoge#m1" | |
x.m1 | |
rescue => e | |
printf "> %s\n", e.inspect | |
end | |
begin | |
puts "-- Calling Hoge#m2" | |
x.m2 | |
rescue => e | |
printf "> %s\n", e.inspect | |
end | |
begin | |
puts "-- Accessing x.a=" | |
x.a = 100 | |
rescue => e | |
printf "> %s\n", e.inspect | |
end | |
y = Foo.new | |
begin | |
puts "-- Calling Foo#m1" | |
y.m1 | |
rescue => e | |
printf "> %s\n", e.inspect | |
end | |
def y.a() | |
puts "Hahaha!!" | |
end | |
begin | |
puts "-- Calling y.m1" | |
y.m1 | |
rescue => e | |
printf "> %s\n", e.inspect | |
end |
This file contains 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
$ ruby hoge.rb | |
-- Calling Hoge#m0 | |
Pooh! | |
-- Calling Hoge#m1 | |
Bra! | |
nil | |
-- Calling Hoge#m2 | |
> #<NoMethodError: private method `a' called for #<Hoge:0x0000560e49600038>> | |
-- Accessing x.a= | |
> #<NoMethodError: private method `a=' called for #<Hoge:0x0000560e49600038>> | |
-- Calling Foo#m1 | |
> #<NameError: undefined local variable or method `a' for #<Foo:0x0000560e4955d888>> | |
-- Calling y.m1 | |
Hahaha!! | |
nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment