Search code examples
rubyirb

Why does the array return a random boolean during the enumeration of the full_name, but not in ruby console? irb


Why does the array ( within the map block ) only return [true, true, false] if executed in ruby console as: x = [(rand 2)==1, (rand 5)==3, (rand 11)==6] then x, x, x?

first = "stephanie"
last = "devenport"
middle = "Lbp"

full_name = "#{first} #{middle} #{last}"

puts "#{full_name}\s\s\s\s\s"
.rstrip.gsub(' ', '').split(//)
.map{ |char| [(rand 2)==1, (rand 5)==3, (rand 11)==6].any? ? "#{char + ['~', '%', '^', '#'].sample}" : "#{char.upcase + ['-', '_'].sample}" }.join.chop

run within terminal returns => S_t~e~p~h#A_n~i^E_L_b~P-d~e^v#E_n%p~o~R-T


Solution

  • x = [(rand 2)==1, (rand 5)==3, (rand 11)==6]
    

    This constructs an array with three elements and stores it in x. The values in that array are random, but they are determined when the array is constructed. Whenever you look at x it will always be the same three element array, because the random calls have already been made and the result has been stored in the array.

    The problem is that x is just a pointer to some values in memory. You can't "call" it. To get a different result every time, you need x to be a method

    def x
      [(rand 2)==1, (rand 5)==3, (rand 11)==6]
    end