6 ms·
This is not idiomatic ruby, you would do class Stuff attr_reader :list def initialize @list = [1, 2, 3, 4] end end Then:
by dorianmariefr 5y ago
This is not idiomatic ruby, you would do
class Stuff
attr_reader :list
def initialize
@list = [1, 2, 3, 4]
end
end
Then:
Stuff.new.list.each { |item| ... }
Stuff.new.list.map { |item| ... }
Stuff.new.list.select { |item| ... }
And if you want top-level each/map/select methods, you could do
delegate :each, :map, :select, to: :list
- bwilliams 5y agoIt's also worth mentioning the Enumerable module that can be mixed in to classes, which gives you `map`, `select`, and much more for free by implementing `each`. https://ruby-doc.org/core-3.0.2/Enumerable.html https://ruby-doc.org/core-3.0.2/Enumerable.html
- softwaredoug 5y agoAuthor here, nice! TIL :)
- stouset 5y agoI have written Ruby professionally for like fifteen years and I have not once witnessed a `for` loop. I’m genuinely confused as to where you picked this up. Enumerator and Enumerable are endemic.
- vidarh 5y ago~15 years here too, and I can't remember my last for loop either. I think for loops are mostly used in Ruby by people that picked it up in other languages first and simply never unlearned it.
- halostatue 5y agoAlmost twenty years here. I have definitely seen and used `for` loops, but they are the _exception_ and usually used in one-off scripts.
- xtracto 5y agoI would actually say that if I found a for loop in Ruby, it will be a code smell.
- retbull 5y agoFrom an entirely tongue in cheek perspective isn't all ruby idiomatic.
- werdnapk 5y agoIncluding `Enumberable` and implementing `each` gets you all those other methods for "free". class Stuff include Enumerable def initialize @list = [1, 2, 3, 4] end def each @list.each{ yield _1 } end end
- deleted 5y ago[deleted]
- gfunk911 5y agoExactly. It is an interesting idea, but it makes me question the examples when `Enumerable` does not appear in the post.
- bullfightonmars 5y agoI thought the examples were just for illustration about how iteration works in Ruby.
- rplnt 5y agoWouldn't it be similar to use this in the python example? class Stuff(list): pass kinda makes the article pointless. List obviously only serves as an easy to understand example, not something you are actually trying to implement.