Created
March 3, 2012 06:35
-
-
Save feiskyer/1964710 to your computer and use it in GitHub Desktop.
Berkeley SaaS class HW1 fun with strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
def palindrome?(string) | |
string.downcase! | |
string=string.gsub(/[^a-z]+/,'') # 正则表达式替换 | |
string==string.reverse | |
end | |
p palindrome?('thissiht') | |
def count_words(string) | |
string.downcase! | |
scan=string.scan(/[a-z]+/) # 搜索所有匹配正则表达式的子串 | |
count={} | |
scan.each do |x| | |
if count.has_key?x then # has_key? | |
count[x]=count[x]+1 | |
else | |
count[x]=1 | |
end | |
end | |
count | |
end | |
p count_words('aslkdflas sadf sadsf sadf sadf e c e c ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment