El nino
El nino

Reputation: 239

Adding 'a' or 'an' to a randomly generated string

How do I add 'a' or 'an' to a randomly generated string?

The random generator is post[rand(post.length)].

How do I add 'a' or 'an' to the above result automatically when the post is starting with either a vowel or a consonant?

Upvotes: 1

Views: 278

Answers (3)

Perry Horwich
Perry Horwich

Reputation: 2846

Interesting. It seems to me that the algorithm here must look at the phonetic pronunciation of the beginning of the word that follows 'a' or 'an.' Just looking at consonants and vowels will not be enough. For example, here are some obvious choices and some exceptions to consider:

a one time thing
a unit of measure
a heavy concept
a high opinion
an egg to beat
an historic moment
an honest man
an owner of things
an eye for an eye

I suppose the answer to the OP will result from answering, "Is there an algorithm for describing the phonetic pronunciation of a word?" If the word to follow begins with a vowel sound, then use 'an' Otherwise, use 'a'

I wonder if this would help: http://creativyst.com/Doc/Articles/SoundEx1/SoundEx1.htm

Upvotes: 2

Paploo
Paploo

Reputation: 661

if string contains your randomly generated string, then new_string will contain an output string with the word 'a' or 'an' in front of it:

new_string = (string=~/^[aeiou]/i ? 'an ' : 'a ') + string

This method does not take into account the case of the initial value on the input string, and try to substitute appropriately. This is only an issue if you have to deal with the beginnings of sentences.

In the even that you do need to deal with the beginnings of sentences, I would recommend that you keep it simple and take the straight-forward method of checking to see if the first letter is a capital, and then building the new_string a little differently in each case: for a lowercase value, do like above, but for an uppercase value, you should downcase the first letter of the input string, and upcase the A in the ternary conditional.

Lastly, note that my example code isn't safe: it assumes that string is already a string object, and not something else (like nil). How you handle bad input is dependent on what you are doing, but a .to_s on each call to string would at least keep it from crashing.

Upvotes: 0

knut
knut

Reputation: 27875

I understand when the post is starting with vowel or a consonant as: _If it start with a letter (no number or special sign).

This should modify your string:

  (randomstring << 'a') if randomstring =~ /\A\w/i

Or with a little testexample:

%w{
  ebbbbb
  debbbbb
  .debbbbb
}.each{|randomstring|
  (randomstring << 'a') if randomstring =~ /\A\w/i
  p randomstring 
}

Upvotes: 0

Related Questions