Forum: Ruby My Boggle Solver: I welcome any tips and tricks!

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
on 2008-02-16 06:35
```So, I wrote a Boggle solver so that I could win at Scramble and
Griddle on Facebook, and it works great! However, I'm pretty new at
Ruby, so if you know any "rubyisms" or "ruby ways" that would help
clean up my program, feel free to give some pointers =) Code below:

\$words = {}
\$stems = {}
File.open("enable.txt","r").each do |line|
word = line.chomp
\$words[word] = true

0.upto(word.size-2) do |i|
\$stems[word[0..i]] = true
end
end

puts "Enter Boggle board as a string of letters:"
letters = gets.chomp

\$H = 4
\$W = 4
if letters.size != \$H*\$W
puts "Wrong board size."
exit
end

i=0
\$board = Array.new(\$H) { Array.new(\$W) }
0.upto(\$H-1) do |h|
0.upto(\$W-1) do |w|
\$board[h][w] = letters[i..i]
i+=1
end
end

\$used = Array.new(\$H) { Array.new(\$W) { false } }

\$found = {}
def solve(h, w, word = '')
\$used[h][w] = true
word += \$board[h][w]
\$found[word] = true if word.size > 2 and \$words[word]

if \$stems[word]
-1.upto(1) do |r|
-1.upto(1) do |c|
y = h+r
x = w+c
next unless (0..\$H-1) === y
next unless (0..\$W-1) === x
next if \$used[y][x]
solve(y, x, word)
end
end
end

\$used[h][w] = false
end

0.upto(\$H-1) do |h|
0.upto(\$W-1) do |w|
solve(h,w)
end
end

found_words = \$found.keys.sort_by { |x| x.size }
found_words.each { |x| puts x }
puts
\$board.each { |x| puts x.to_s }```
on 2008-02-16 07:20
```On Feb 15, 11:34 pm, Stedwick <philip.broc...@gmail.com> wrote:

> \$words = {}
> \$stems = {}
> File.open("enable.txt","r").each do |line|
>   word = line.chomp
>   \$words[word] = true
>
>   0.upto(word.size-2) do |i|
>     \$stems[word[0..i]] = true
>   end
> end

IO.foreach("enable.txt"){|word|
word.strip!
\$words[word] = true
(0...word.size).each{|i|
\$stems[ word[0,i] ] = true
}
}```
on 2008-02-16 07:32
```On Feb 16, 12:17 am, William James <w_a_x_...@yahoo.com> wrote:
> >   end
> > end
>
> IO.foreach("enable.txt"){|word|
>   word.strip!
>   \$words[word] = true
>   (0...word.size).each{|i|
>     \$stems[ word[0,i] ] = true
>   }}

Shorter:

IO.foreach("data"){|word|
\$words[ word.strip! ] = true
(0...word.size).each{|i|
\$stems[ word[0,i] ] = true
}
}```
on 2008-02-16 08:45
```> \$words = {}

IMHO you might also want to try to avoid using global variables. A
better solution usually is to use "normal" variables or to wrap it up
in a class/module and use class/instance variables. Or collect the
parameters in a hash and pass that around.```
This topic is locked and can not be replied to.