Skip to content

Instantly share code, notes, and snippets.

@natanio
Last active December 28, 2015 15:39
Show Gist options
  • Save natanio/7522848 to your computer and use it in GitHub Desktop.
Save natanio/7522848 to your computer and use it in GitHub Desktop.
def mix(syllable1, syllable2)
arr = [syllable1, syllable2]
t = 3
until t == 13 do
t.times do
index = rand(2)
print arr[index] +', '
end
puts
t += 1
end
end
puts "What is syllable 1?"
s1 = gets.chomp
puts "What is syllable 2?"
s2 = gets.chomp
filename = "#{s1} and #{s2} Mix.rb"
target = File.open(filename, 'w')
output = mix(s1,s2)
target.write(output)
puts "Done!"
@mikekreeki
Copy link

Don't forgot to close the file after you're done working with it:

target = File.open(filename, 'w')
target.write(output)
target.close

Maybe the better way would be to use a block, then Ruby closes the file automatically.

File.open(filename, 'w') do |f|
  f.write(output)
end

Both examples are equivalent.

@mikekreeki
Copy link

Also although the method outputs correct data to the screen, it does not return it, so output gets assigned the value of nil.

> mix('a','b')
# => nil 

And for this reason the saved file is blank, you are writing nil to a file.

Quick and dirty solution to this problem might be something like this:

def mix(syllable1, syllable2)
  arr = [syllable1, syllable2]
  t = 3

  # Initialize a variable where we're going to store the result
  text = ''

  until t == 13
    t.times do
      index = rand(2)
      str = arr[index] + ', '
      print str

      # append the string to the result
      text += str
    end
    puts

    # Append new line to the result
    text += "\n"
    t += 1
  end

  # Return the result
  text
end

@mclosson
Copy link

def mix(*syllables)
  t = 3
  result = []

  until t == 13 do
    t.times do
      result << syllables[rand(2)]
    end

    t += 1
  end

  result.join(', ')
end

puts "What is syllable 1?"
s1 = gets.chomp

puts "What is syllable 2?"
s2 = gets.chomp

filename = "#{s1} and #{s2} Mix.txt"

target = File.open(filename, 'w')

output = mix(s1,s2)

target.write(output)

puts "Done!"

@denisdefreyne
Copy link

Small semi-unrelated tip: if you change the file name in the gist to something that ends with .rb, you will get pretty syntax coloring.

@natanio
Copy link
Author

natanio commented Nov 19, 2013

@mikekreeki Thanks for the detailed help and solution! I couldn't figure out why it was making a blank file, but now see that I need to save it to a variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment