Reputation: 85
I need to create a Struct with multiple fields (based on a long string). Here is what I have so far:
s = "a1|b2|c3|"
a = s.split("|")
b = []
a.each { |e|
b.push(e.to_sym)
}
Str = Struct.new(*b)
Anyway to make it shorter?
Upvotes: 0
Views: 75
Reputation: 237110
The pattern b = []; a.each {|e| b << (do something with e) }
can always be shortened to a use of map
. So:
s = "a1|b2|c3"
b = s.split('|').map {|e| e.to_sym }
Or, even more tersely:
s = "a1|b2|c3"
b = s.split('|').map(&:to_sym)
Upvotes: 1
Reputation: 168269
Here it is:
Str = Struct.new(*"a1|b2|c3|".split("|").map(&:to_sym))
Upvotes: 2