Тема: Вивчення Ruby & Ruby on Rails
Оце читаю зараз цей сайт/книгу https://bparanj.gitbooks.io/ruby-basics … _vars.html
і спершу помітив такий прекол
some_method = 3.method(:+)
some_method.call(5) // поверне 8тобто, воно по факту створює метод, який зав'язаний на інстансі конкретного клясу Integer, який має значення 3.
Потім подивився на
3.methodsі воно показало мені величезний список методів, які висять на клясі Integer, і серед них були -, + і всяке таке. І от виявилось, шо +, - та інші оператори по факту є методами... Тобто, мона їх самому писать.
class Bread
def initialize
puts 'Bread created'
end
def +(other)
return unless other.is_a?(Butter)
puts 'creating a sandwich with bread and butter...'
Sandwich.new
end
end
class Sandwich
def initialize
puts 'Sandwich created!'
end
end
class Butter
def initialize
puts 'Butter created'
end
end
bread = Bread.new
butter = Butter.new
result = bread + butterвиведе
Bread created
Butter created
creating a sandwich with bread and butter...
Sandwich created!