I have a file that looks like this:
[noahc:~/projects/wordsquares] master(+87/-50)* ± cat wordlist/test_word_list.txt card apple joe bird card dart area rear birdbird after boat swim north abbe byes beep If I open up an irb session, I can do:
2.0.0p247 :001 > file = File.open('./wordlist/test_word_list.txt', 'r') => #<File:./wordlist/test_word_list.txt> 2.0.0p247 :002 > file.readlines => ["card\n", "apple\n", "joe\n", "bird\n", "card\n", "dart\n", "area\n", "rear\n", "birdbird\n", "after\n", "boat\n", "swim\n", "north\n", "abbe\n", "byes\n", "beep \n", "\n"] But, now I have a class called WordSquareGenerator:
class WordSquareGenerator require 'pry' require 'pry-nav' require './lib/word_list_builder.rb' def initialize(n, file_location) @size_of_square = n @file = load_file(file_location) @word_stem_hash = WordListBuilder.new(n, @file).word_stem_hash @word_list = nil end def word_square_word_list binding.pry @file.each do |w| binding.pry @word_list ? break : solve_for_word_list([word]) end binding.pry end def is_list_valid?(list) (0..@size_of_square - 1).each do |n| (0..@size_of_square - 2).each do |m| return false if list[n][m] != list [m][n] end end @generated_list = list unless @generated_list end def solve_for_word_list(word_array) if word_array.length == 4 @word_list = word_array elsif @word_list else next_words = @word_stem_hash[word_array.map{|w| w[word_array.length]}.join] next_words.each do |word| solve_for_word_list(word_array + [word]) end end end private def load_file(file_location) File.open(file_location, 'r') end end When I run the word_square_word_list method and hit the first binding.pry, I can do:
2.0.0 (#<WordSquareGenerator:0x007ff3f91c16b0>):0 > @file.readlines => [] and I get an empty array for readlines. How can it be that I'm getting two different results doing the same thing, except one is inside that class and the other isn't?
load_fileand use aFile.openblock that wraps the call toWordListBuilder.new. Also, don't use ternary statements for flow control:@word_list ? break : solve_for_word_list([word])should bebreak if @word_listfollowed bysolve_for_word_list([word]).breakor a method call, obfuscates what you're really doing, which is breaking if a value is set, or calling another method. In reality, using anif/elsewould be just as bad. Use a trailingiftobreakor fall through to the next method call.