Skip to content

Instantly share code, notes, and snippets.

@fijiaaron
Last active February 26, 2019 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fijiaaron/61461c984489201af6432fb57daed92b to your computer and use it in GitHub Desktop.
Save fijiaaron/61461c984489201af6432fb57daed92b to your computer and use it in GitHub Desktop.
RubyAccessors created by fijiaaron - https://repl.it/@fijiaaron/RubyAccessors
class Foo
# initialize instance variables
def initialize(bar="bar", baz="baz")
@bar = bar
@baz = baz
end
end
class Foo
# initialize instance variables
def initialize(bar="bar", baz="baz")
@bar = bar
@baz = baz
end
# generate default getters and setters
attr_accessor :bar, :baz
end
class Foo
# initialize instance variables
def initialize(bar="bar", baz="baz")
@bar = bar
@baz = baz
end
# generate default getters and setters
attr_accessor :bar, :baz
# add custom getter
def bar()
return @bar.capitalize()
end
end
class Foo
# initialize instance variables
def initialize(bar="bar", baz="baz")
@bar = bar
@baz = baz
end
# generate default getters and setters
attr_accessor :bar, :baz
# add custom getter
def bar()
return @bar.capitalize()
end
# add custom setter
def baz=()
@baz = @baz.reverse()
end
end
require_relative("test.rb")
# initialize class with private instance variables
class Foo
def initialize(bar="bar", baz="baz")
@bar = bar
@baz = baz
end
end
# create global foo to test
$foo = Foo.new()
test("no accessors")
# add default getters and setters
class Foo
attr_accessor :bar, :baz
end
test("attr_accessor")
# add custom getter
class Foo
def bar()
@bar.upcase()
end
end
test("custom getter")
# add custom setter
class Foo
def baz=(baz)
@baz = baz.reverse()
end
end
# set instance variable
$foo.baz = "baz"
test("custom setter")
Demonstrate how to use getters and setters in Ruby
def test(message)
begin
puts "Test with #{message}"
puts $foo.bar, $foo.baz
rescue StandardError => e
puts e.message
end
puts("\n")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment