toy
toy

Reputation: 12141

How do I construct an object in ruby Array Map?

class TestClass
  attr_accessor :name, :id
end


values = ["test1", "test2"]

mapped_values = values.map{|value|
  test_class = TestClass.new
  test_class.name = value
  test_class.id = #some random number
  return test_class
}

puts mapped_values

Obviously this won't work, it will just return the first value and not the whole of newly constructed list. I have this test script which what I wanted to achieve is that it returns the list of TestClass with value name and id in it, from the Array.map operation. I'm just trying to find the best way to do it in Ruby.

I could do something like this

tests = []

values.each do |value|
   test_class = TestClass.new
   test_class.name = value
   test_class.id = #some random number
   tests << test_class
end

I believe there must be a better way of doing this?

Upvotes: 2

Views: 94

Answers (1)

user946611
user946611

Reputation:

If you want to use map, remove the return call.

mapped_values = values.map{|value|
  test_class = TestClass.new
  test_class.name = value
  test_class.id = #some random number
  test_class
}

The block being passed is a Proc and Procs doesn't allow explicit return calls. Please refer Why does explicit return make a difference in a Proc? for more information

Upvotes: 3

Related Questions