Loop improvement

E

EdUarDo

Hi all, I have this code:


class Test
def testA
home_squad = home.squad.to_a
###########################################
# Could improve this?
###########################################
for i in 0...11
home.tactic.set_player(i, home_squad[0])
end
end
end

class Tactic
def set_player(counter_id, player_id)
@counters[counter_id].player_id = player_id
end
end

Having that home.squad is a Hash object, and @counters an Array,
is there an easy way to do what I'm trying to do?

In loop for of testA method I want to change the player_id attribute of
objects contained in @counters array. Could I define an iterator to simplify
the sentence?
 
J

James Edward Gray II

Hi all, I have this code:


class Test
def testA
home_squad = home.squad.to_a
###########################################
# Could improve this?
###########################################
for i in 0...11
home.tactic.set_player(i, home_squad[0])
end
end
end

class Tactic
def set_player(counter_id, player_id)
@counters[counter_id].player_id = player_id
end
end

Having that home.squad is a Hash object, and @counters an Array,
is there an easy way to do what I'm trying to do?

In loop for of testA method I want to change the player_id
attribute of
objects contained in @counters array. Could I define an iterator to
simplify
the sentence?


Here's one thought:

class Test
def testA
home_squad = home.squad.to_a
home_squad.each_with_index do |squad, i|
home.tactic.set_player(i, squad.first)
end
end
end

class Tactic
def set_player(counter_id, player_id)
@counters[counter_id].player_id = player_id
end
end

Another idea it to expose the @counters from Tactic:

class Test
def testA
home_squad = home.squad.to_a.map { |e| e.first }
home.tactic.counters.each { |c| c.player_id =
home_squad.shift }
end
end

class Tactic
attr_reader :counters
end

Or, you could delegate the iteration:

class Test
def testA
home_squad = home.squad.to_a.map { |e| e.first }
home.tactic.players { |c| c.player_id = home_squad.shift }
end
end

class Tactic
def players( &block )
@counters.each(&block)
end
end

Hope that gives you some new ideas.

James Edward Gray II
 
E

EdUarDo

James said:
Hope that gives you some new ideas.

All are good ideas. Sometimes I need to cry because of my rigid brain :(,
well, I think I need more experience with Ruby.
 
J

James Edward Gray II

Which is the e's class?

Whatever the class of home_squad[n] is. map() just walks the Array,
replacing the elements.

It looked like an Array to me, by the way you were using it.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top