Domanda

I need to discover if the first element of a string is a char or not. Example:

string_1 = "Smith has 30 years"   ----->  TRUE (first element is a character)
string_2 = "20/12/2013 Good Day"  ----->  FALSE (first element is not a character)
string_3 = "<My name is John>"    ----->  FALSE (first element is not a character)

Using ".initial" I'm able to access to the first element of each string, but then I don't know to do the test

È stato utile?

Soluzione

If you mean checking if first element in string is letter, you could do:

string[0].match(/[a-zA-Z]/)

or, as Arup Rakshit suggested, you can use i option in your regexp to ignore case:

string[0].match(/[a-z]/i)

These lines will return either MatchData if tested string starts with letter or nil if it doesn't. If you want true and false values, you can do:

!!string[0].match(/[a-z]/i)

Altri suggerimenti

This detects if the initial character is a letter (alphabet or underscore; not whether it is a character).

string =~ /\A\w/

You can do as below :

string[/\A[a-z]/i]

Look this - str[regexp] → new_str or nil

In Ruby nil and false object considered as having falsy value.

Or use Regexp#=== as below :

irb(main):001:0>  /\A[a-z]/i === 'aaa'
=> true
irb(main):002:0>  /\A[a-z]/i === '2aa'
=> false

You can do like following:--

regex = /[a-zA-Z]/

str[0][regex]
#=> either a letter or nil

str[0][regex].kind_of?(String)
#=> true if first letter matches the regex or false if match return nil.

Just try,

2.0.0-p247 :042 > /^[a-zA-Z]/ === 'Smith has 30 \n years'
 => true 
OR
2.0.0-p247 :042 > /\A[a-zA-Z]/ === "Smith has \n 30 years"
 => true


2.0.0-p247 :042 > /^[a-zA-Z]/ === '20/12/2013 \n Good Day'
 => false 
OR
2.0.0-p247 :042 > /\A[a-zA-Z]/ === "20/12/2013 \n Good Day"
 => false


2.0.0-p247 :042 > /^[a-zA-Z]/ === '<My name is \n John>'
 => false 
OR
2.0.0-p247 :042 > /\A[a-zA-Z]/ === "<My name \n is John>"
 => false
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top