Forum: Ruby Count number of letters(only) and the other code number of words(only)

63f33bf06c2fa61f059ca295cb68c6f0?d=identicon&s=25 Miroslav Stoyanov (miroslav_s46)
on 2017-02-11 11:40
I want to make the first code count only letters, how can I do that?

#----------give the number of the characters
  len = info.length
  len1 = len
  readFile("wiki.txt")
  @info = info + "" + $myinfo
  len = @info.length(&:length)
  len2 = len - 1
  len3 = len2 - len1
  @words = len3.to_i
  file00=File.open("wiki.txt","r")
   info=""
   file00.each do |line|
      info=info + line
  end

   file00.close
   $myinfo = info
   @info = $myinfo

   And this below should count only words, but it count ("."!"@"?";"
etc.. symbols too) symbols and space.
   #------------------------------gives the number of words 2 options
   file1=File.open("wiki.txt","r")
   len2=file1.read.split.length
   @word=len2.to_s
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2017-02-13 18:02
A simple, but not necessarily correct answer, would be to use
String#count
(http://ruby-doc.org/core-1.9.3/String.html#method-i-count). The crucial
point here is, that you did not explain what you consider a letter, and
because of this, I don't know whether String#count will work for you.

For finer control, you should specify in a regexp what is a letter for
you and use String#scan to collect them. For example, if you call a
"character"  everything which is in the Posix character class 'alpha',
you could do a

    number = 0
    yourstring.scan(/[[:alpha:]]/) { number+=1 }
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.