Tony
Tony

Reputation: 1011

Storing output into a variable to be used in an array

A snippet of my code below flips a coin and outputs a result of 10 total heads or tails.

(e.g. Heads Tails Heads Tails...)

I'd like to store this into a variable where I can put it into an array and use its strings.

%w[act] only outputs the string "act". How can I get that line of code to output my array of strings from the line act = coin.flip?

Updated and added full code

class Coin

  def flip
    flip = 1 + rand(2)
      if flip == 2 
        then puts "Heads"
      else
        puts "Tails"
      end
  end   

end

array = []

10.times do
  coin = Coin.new
  array << coin.flip 
end

puts array

Upvotes: 0

Views: 2148

Answers (2)

mu is too short
mu is too short

Reputation: 434616

This:

10.times do
  coin = Coin.new
  act = coin.flip
end

doesn't produce an array. It simply creates ten coin flips and throws them all away, the result of that expression is, in fact, 10. If you want an array, you'll need to build one.

You could take Douglas's approach or try something a bit more idiomatic.

The Integer#times method returns an enumerator so you can use any of the Enumerable methods on it rather than directly handing it a block. In particular, you could use collect to build an array in one nice short piece of code:

a = 10.times.collect { Coin.new.flip }

That gives you 10 flips in the Array a and then you can puts a or puts a.join(', ') or whatever you want.

The %w[] won't work because that's for generating an Array of whitespace separated words:

%w[] Non-interpolated Array of words, separated by whitespace

So %w[a b c] is just a nicer way of saying ['a', 'b', 'c'] and the words within %w[] are treated as single quoted strings rather than variables or method calls to be evaluated.


Seems that there is some editing going on. You'll also want to modify your flip method to return the flip rather than print it:

def flip
  flip = 1 + rand(2)
  if flip == 2 
    "Heads"
  else
    "Tails"
  end
end

Then you'll get your Heads and Rails in the array.

Upvotes: 2

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

Put the act results into an array.

arr = []

10.times do
  coin = Coin.new
  arr << coin.flip
end

p arr # => [...]

Upvotes: 1

Related Questions