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

    Join Date
    Oct 2013
    Rep Power

    Basic ruby program to count chars

    Heyya, So I got a new assignment in my uni, but so far I have only learned c++ and suddenly they throw us into ruby, (assholes!)

    I got the program this far

    print "write a sentence: "
    sentence= gets
    puts "#{setning}"
    "#{setning}".each_char {|c| print c, ' ' }

    But I dont know where to go from here, the program should do as follows:

    If I write hello world

    as input then the program should read out
    1*d, 1*e, 1*h, 3*l, 2*o, 1*r, 1*w.

    so, only lower case and in alphabetical order without showing 0*f for example.

    in c++ i would do something like fin.eof{ if a( a++)

    and so on, not 100% sure how but, can anyone help me with this this is so confusing

    Maybe a array would be a good idea? but I wouldnt know how to utilize it or how to make it in ruby
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Rep Power

    this requires no Ruby-specific functionalities at all. If you can write down the pseudo-code, you shouldn't have any problems implementing it in Ruby.

    So what's the pseudo-code? Or C++ code, if you want.
  4. #3
  5. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Rep Power
    Looks like your assignment wasn't so important after all.

    Anyway, this is actually an interesting task, because it shows the versatility of Ruby. You can solve this in a classical way using a Hash. Or you can take advantage of Ruby's highlevel methods.

    By far the simplest and shortest solution would be to use String#char. But I guess that's kinda cheating.

    ruby Code:
    input = "Hello world"
    ('a'..'z').each do |char|
      count = input.downcase.count char
      puts "#{count} * #{char}" if count > 0

IMN logo majestic logo threadwatch logo seochat tools logo