0

this is my first post ever to stack overflow so I apologize if this is a poor question and if I incorrectly posted the code below.

I'm fairly new to computer programing and was trying to apply the use of the .each method in from Ruby to write out song lyrics. There is this ridiculous/awesome/idiotic song by Little John called, "Turn down for what?" The song basically repeats the same two lines over and over again.

I wanted to see if I could correctly apply the knowledge of the .each method from Ruby to re-write the song lyrics in the form of code.

The output puts out exactly the way I want to it to appear. However I did feel that I was essentially typing the same lines over and over again. Is there a more efficient way to do this?

Thanks for your help and please let me know if this question needs to be asked differently.

def turn_down_for_what

  puts ""
  fire_up = "Fire up, your loud, another round of shots!"

  chorus = "Turn down for what!!!"

  puts ""

  puts fire_up

  puts ""

  4.times do
      puts chorus
  end

  puts ""

  puts fire_up

  puts ""

  4.times do
      puts chorus
  end

  puts ""

  3.times do
      puts fire_up
  end

  10.times do
      puts "Shots! "
  end
  puts ""
  4.times do
      puts chorus
  end
end

turn_down_for_what
1

Since the process is just a sequence of doing puts for a given phrase a specified number of times you could store the sequence (and repetitions) in an array and then iterate through the array...

def turn_down_for_what

  fire_up = "Fire up, your loud, another round of shots!"

  chorus = "Turn down for what!!!"

  song = [[''], [fire_up], [''], [chorus, 4], 
          [''], [fire_up], [''], [chorus, 4], 
          [''], [fire_up, 3], ["Shots!", 10], 
          [''], [chorus, 4]]

  song.each {|line| (line[1]||1).times {puts line[0]}}

end

turn_down_for_what

It's an array of arrays, the first element of each sub array is the line to puts, the second element is the number of times. Note that if the number of times isn't specified, we assume 1 (line[1] || 1 means the second element or the integer 1 if the second element is nil.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.