0

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?

1
  • 3
    Whenever it's a question about "how do I improve this", that's a flag that the question probably belongs on codereview.stackexchange.com. Commented Dec 19, 2013 at 3:11

2 Answers 2

2

Here it is:

Str = Struct.new(*"a1|b2|c3|".split("|").map(&:to_sym))
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.