by tcopeland · 8y ago · 0 comments
Focus on strong object oriented programming
What I've learned from Ruby is to favor functional programming concepts - minimize side effects, isolate state mutation, etc. Ruby is definitely OO, but when my Ruby code is more functional it's less buggy, easier to understand and move around, and generally less convoluted.All those methods, and reactive patterns (Observer and such) were already present in Smalltalk-80.
a = (1..1000).lazy.select(&:even?).map{|i| i*2 }.map{|i| i + 1 }.map(&:to_s).map(&:reverse)
There is no benefit from lazy if you do `a.join(",")`, since that iterates over the entire sequence. But if you do `a.take(10)` or `a.detect{|s| s == "14" }`, the chain will only be executed for each item in turn until 10 elements are produced or an element is the string "14", respectively.The lazy version basically turns into
a = ""
(1..1000).each { |i|
next if i.odd?
i *= 2
i += 1
a << i.to_s.reverse + ", " # ya ya, trailing comma
}
Where as the non lazy version turns into: odds = []
(1..1000).each { |i| odds << i if i.even? }
doubled = []
odds.each { |o| doubled << o * 2 }
incremented = []
doubled.each { |d| incremented << d + 1 }
strs = []
incremented.each { |i| i.to_s }
a = ""
strs.each{ |s| a << s.reversed + ", " }
Which means that you have you went from N iterations to 5*N iterations, with 5 intermediate arrays in this case.I'm about half way done. When I'm done, I'll post it on HN, but if you are interested here is what I've got so far: https://github.com/ygt-mikekchar/oojs/blob/master/oojs.org If anyone ends up reading it, I'm very happy to receive criticism, so feel free to leave an issue.
Its not about what is possible, we're all familiar with the turing completeness of everything. It's about what is: the default + easy + encouraged in the ecosystem.
I'm run into the downside, though, that Ruby isn't optimized for immutable operations - tons of object instances created. I've needed to 'pythonize' my Ruby code in the worst cases - using mutable functions to dramatically reduce memory usage.