Created
August 9, 2012 13:03
-
-
Save sycobuny/3304011 to your computer and use it in GitHub Desktop.
Demonstrating various differences between class and instance methods in Ruby
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
#!/usr/bin/env ruby | |
class SomeClass | |
def self.add_two_numbers(one, two) | |
one + two | |
end | |
def add_two_numbers(one, two) | |
self.class.add_two_numbers(one, two) | |
end | |
end | |
obj = SomeClass.new | |
puts obj.add_two_numbers(1, 2) | |
__END__ | |
$ ./ex.rb | |
3 | |
$ |
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
#!/usr/bin/env ruby | |
class SomeClass | |
def self.call_private_method(obj) | |
obj.send(:set_value, 5) | |
end | |
def self.retrieve_value(obj) | |
obj.instance_variable_get(:@value) | |
end | |
####### | |
private | |
####### | |
def set_value(val) | |
@value = val | |
end | |
end | |
myinstance = SomeClass.new | |
SomeClass.call_private_method(myinstance) | |
puts SomeClass.retrieve_value(myinstance) | |
__END__ | |
$ ./ex2.rb | |
5 | |
$ |
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
#!/usr/bin/env ruby | |
class SomeClass | |
def test_setup! | |
@a = 1 | |
@b = 2 | |
@c = 'and now for something completely different' | |
end | |
def debug_vars | |
instance_variables.sort.each do |var| | |
puts "#{var}: #{instance_variable_get(var).inspect}" | |
end | |
end | |
end | |
obj = SomeClass.new | |
obj.test_setup! | |
obj.debug_vars | |
__END__ | |
$ ./ex3.rb | |
@a: 1 | |
@b: 2 | |
@c: "and now for something completely different" | |
$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment