Last active
August 3, 2022 03:57
-
-
Save leandronsp/fb6c171d9d0f700b0ba5f124ead7f223 to your computer and use it in GitHub Desktop.
OOP in Ruby without classes
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
leandro = new_instance(Account, "Leandro", 0) | |
john = new_instance(Account, "John", 100) | |
send_message(leandro, :deposit, 50) | |
send_message(john, :deposit, 10) | |
send_message(leandro, :print_balance) | |
# => Leandro's balance: 50 | |
send_message(john, :print_balance) | |
# => John's balance: 110 |
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
Account = { | |
properties: [:name, :balance], | |
methods: { | |
deposit: lambda do |context, amount| | |
context[:state][:balance] += amount | |
end, | |
print_balance: lambda do |context| | |
name = context[:state][:name] | |
balance = context[:state][:balance] | |
puts "#{name}'s balance: #{balance}" | |
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
def new_instance(template, *args) | |
state = | |
template[:properties] | |
.zip(args) | |
.to_h | |
template.merge(state: state) | |
end | |
def send_message(object, message, *args) | |
return unless object[:methods].has_key?(message) | |
object[:methods][message].call(object, *args) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment