I can’t seem to get this to work, I think it may not see the
‘my_file.txt’ in the folder because I am on a Mac?
Here is the script:
hidden_text.rb
devdaily.com
feel free to use this program however you like.
def get_file_as_string(filename)
data = ‘’
f = File.open(filename, “r”)
f.each_line do |line|
data += line
end
return data
end
def print_odd(count)
return true if count.modulo(2) != 0
return false
end
def print_even(count)
return true if count.modulo(2) == 0
return false
end
#------------ word-based output ----------------#
def print_even_words(text)
words = text.split
count = 1
words.each { |w|
print w if print_even(count)
print " "
count = count + 1
}
end
def print_odd_words(text)
words = text.split
count = 1
words.each { |w|
print w if print_odd(count)
print " "
count = count + 1
}
end
def print_nth_words(text, n, offset=0)
words = text.split
count = offset
while (count < words.length-offset) do
print words[count]
print " "
count = count + n
end
end
def print_fib_words(text)
words = text.split
fib_last = 1
fib_older = 1
fib_next = 1
while (fib_next < words.length) do
print words[fib_next-1]
print " "
fib_next = fib_last + fib_older #
fib_older = fib_last #
fib_last = fib_next #
return if fib_next >= words.length
end
end
#------------ character-based output ----------------#
def print_odd_chars(text)
words = text.split(//)
count = 1
words.each { |w|
print w if print_odd(count)
count = count + 1
}
end
def print_even_chars(text)
words = text.split(//)
count = 1
words.each { |w|
print w if print_even(count)
count = count + 1
}
end
def print_nth_chars(text, n, offset=0)
words = text.split(//)
count = offset
while (count < words.length-offset) do
print words[count]
count = count + n
end
end
def print_fib_chars(text)
words = text.split(//)
fib_last = 1
fib_older = 1
fib_next = 1
while (fib_next < words.length) do
print words[fib_next-1]
fib_next = fib_last + fib_older
fib_older = fib_last
fib_last = fib_next
return if fib_next >= words.length
end
end
################
MAIN
################
TO-DO: Every method could take an “offset” value.
text = get_file_as_string ‘my_file.txt’
print_odd_words(text)
puts “\n============”
print_even_words(text)
puts “\n============”
print_nth_chars(text,10,1)
puts “\n============”
print_nth_words(text,10)
puts “\n============”
print_fib_words(text)
puts “\n============”
print_fib_chars(text)