Last active
December 28, 2015 15:39
-
-
Save natanio/7522848 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!" |
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
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!"
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.
@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
Don't forgot to close the file after you're done working with it:
Maybe the better way would be to use a block, then Ruby closes the file automatically.
Both examples are equivalent.