ruby - Check if string contains one word or more -


when looping through lines of text, neatest way (most 'ruby') if else statement (or similar) check if string single word or not?

def check_if_single_word(string)    # code here end  s1 = "two words" s2 = "hello"  check_if_single_word(s1) -> false check_if_single_word(s2) -> true 

since you're asking 'most ruby' way, i'd rename method single_word?

one way check presence of space character.

def single_word?(string)   !string.strip.include? " " end 

but if want allow particular set of characters meet your definition of word, perhaps including apostrophes , hyphens, use regex:

def single_word?(string)   string.scan(/[\w'-]+/).length == 1 end 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -