[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

How to count a word in a line

Yusuf Celik

4/19/2007 2:11:00 PM

Hi,
I wonder if there is a way of counting a word in a line using ruby
regexp.
Such as how many "Hi"'s in a line.
Let's say when I enter a line
"Hello and Hi there hey hear my Hi"
It should give me 2, because there are 2 "Hi"'s.
I have something like this but looks awkward.
while line=gets.chomp
cnt = 0
line.split.each {
|v|
if v == 'Hi' then
cnt +=1
end
}
break if cnt > 2
end

Thanks in advance
Yusuf Celik

--
Posted via http://www.ruby-....

4 Answers

Yusuf Celik

4/19/2007 2:17:00 PM

0

Sorry made a mistake
line=gets.chomp
cnt = 0
line.split.each {
|v|
if v == 'Hi' then
cnt +=1
end
}
puts "#{cnt}"

--
Posted via http://www.ruby-....

dblack

4/19/2007 2:25:00 PM

0

Hi --

On 4/19/07, Yusuf Celik <ycelik@oytek.com.tr> wrote:
> Sorry made a mistake
> line=gets.chomp
> cnt = 0
> line.split.each {
> |v|
> if v == 'Hi' then
> cnt +=1
> end
> }
> puts "#{cnt}"

You could do:

line.scan(/\bHi\b/).size

(or \s instead of \b if you want it to be spaces instead of word
boundaries [which can also be hyphens and other punctuation]).


David

--
Upcoming Rails training by Ruby Power and Light:
Four-day Intro to Intermediate
May 8-11, 2007
Edison, NJ
http://www.rubypal.com/event...

M. Edward (Ed) Borasky

4/19/2007 2:29:00 PM

0

Yusuf Celik wrote:
> Sorry made a mistake
> line=gets.chomp
> cnt = 0
> line.split.each {
> |v|
> if v == 'Hi' then
> cnt +=1
> end
> }
> puts "#{cnt}"
>
>
Isn't there some totally unreadable regex that does this? :)

--
M. Edward (Ed) Borasky, FBG, AB, PTA, PGS, MS, MNLP, NST, ACMC(P)
http://borasky-res...

If God had meant for carrots to be eaten cooked, He would have given rabbits fire.


Yusuf Celik

4/19/2007 2:35:00 PM

0

Thanks David,

What can I say I am speechless.
Just 1 line wow.

Thanks anyway
Yusuf
> You could do:
>
> line.scan(/\bHi\b/).size
>
> (or \s instead of \b if you want it to be spaces instead of word
> boundaries [which can also be hyphens and other punctuation]).

--
Posted via http://www.ruby-....