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

    Join Date
    Oct 2013
    Posts
    1
    Rep Power
    0

    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

    #!/usr/bin/ruby
    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
    Posts
    3,957
    Rep Power
    1046
    Hi,

    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.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    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
    end
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo