Skip to content

Instantly share code, notes, and snippets.

@andymatuschak
Forked from ilyanep/some looping stuff.rb
Created July 14, 2010 05:33

Revisions

  1. andymatuschak revised this gist Jul 14, 2010. 1 changed file with 8 additions and 15 deletions.
    23 changes: 8 additions & 15 deletions some looping stuff.rb
    Original file line number Diff line number Diff line change
    @@ -1,21 +1,14 @@
    # Suppose I want to the user to enter names one at a time, until the user enters a blank line,
    # then tell each name that they're awesome. In a typical programming language, my first instinct
    # would be to do:
    # then tell each name that they're awesome.

    while (name = gets.chomp) != ""
    puts name + ", you are so awesome"
    # Yeah, I don't have really a better way of doing that, and that bothers me. I'd do:

    # or perhaps alternatively, to get the names to print afterwards

    names = Array.new
    while (name = gets.chomp) != ""
    names.push name
    a = []
    until (str = gets.chomp?).empty?
    a << str
    end

    names.each do |nom|
    puts "#{nom}, you are so awesome"
    end
    # The key thing that keeps you from using a standard HOM is that you don't know the
    # number of elements you're going to have off the bat.

    # But this is a very C way of doing things, and Ruby is supposed to be more elegant. How would you
    # do this? Seems like there has to be a way of avoiding using a while loop, and it's probably actually
    # really easy, but I'm just being dumb slash don't know Ruby that well.
    # Generators are a pattern for dealing with this: http://en.wikipedia.org/wiki/Generator_(computer_science)
  2. @invalid-email-address Anonymous created this gist Jul 14, 2010.
    21 changes: 21 additions & 0 deletions some looping stuff.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    # Suppose I want to the user to enter names one at a time, until the user enters a blank line,
    # then tell each name that they're awesome. In a typical programming language, my first instinct
    # would be to do:

    while (name = gets.chomp) != ""
    puts name + ", you are so awesome"

    # or perhaps alternatively, to get the names to print afterwards

    names = Array.new
    while (name = gets.chomp) != ""
    names.push name
    end

    names.each do |nom|
    puts "#{nom}, you are so awesome"
    end

    # But this is a very C way of doing things, and Ruby is supposed to be more elegant. How would you
    # do this? Seems like there has to be a way of avoiding using a while loop, and it's probably actually
    # really easy, but I'm just being dumb slash don't know Ruby that well.