Thread: Hangman Game

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    5
    Rep Power
    0

    Hangman Game


    How do you select random words from a list of words using a global variable? Or a different method?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    Use Array#shuffle
    Code:
    irb(main):001:0> letters = ('a'..'z').to_a
    => ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
    irb(main):002:0> letters.shuffle.shift
    => "l"
    irb(main):003:0> letters.shuffle.shift
    => "i"
    irb(main):004:0> letters.shuffle.shift
    => "p"
    irb(main):005:0> letters.shuffle.shift
    => "h"
    irb(main):006:0> letters.shuffle.shift
    => "q"
    If Array#shuffle is not available in your distribution you can 'fake' it with sort_by
    Code:
    irb(main):007:0> letters.sort_by { rand }
    => ["q", "g", "l", "f", "p", "d", "e", "y", "v", "h", "z", "r", "n", "s", "k", "u", "a", "x", "b", "t", "o", "c", "w", "i", "j", "m"]
    irb(main):008:0> letters.sort_by { rand }
    => ["n", "y", "z", "o", "h", "p", "x", "v", "b", "m", "t", "r", "q", "k", "a", "g", "j", "c", "u", "d", "l", "w", "s", "f", "i", "e"]
    The examples above use only letters for brevity, but you can use words as well.
    Code:
    irb(main):010:0> ["A", "List", "Of", "Words"].shuffle
    => ["Words", "List", "Of", "A"]
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    5
    Rep Power
    0

    Thanks but


    im looking for something different. Here is a example

    def initialize(word=nil)
    # if there is a word, use it
    if word != nil
    @word = word
    else
    # otherwise use a random word from the dictionary
    @word = $words
    end

    $words is my global varibale that links my words but i dont know how to randomize it and select one word from my list.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    Originally Posted by Allu_Akbar
    $words is my global varibale that links my words
    That statement doesnt make much sense. What do you mean by links?
    If $words is an array, just shuffle it.
    Code:
    else
       # otherwise use a random word from the dictionary
       @word = $words.shuffle.shift
    end
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog

IMN logo majestic logo threadwatch logo seochat tools logo