Strings and Regular Expressions
——孙琨SealSun
1、问题
Check the documentation on String and Regexp as they could help tremendously with these exercises.
Define a method hello(name) that takes a string representing a name and returns the string "Hello, " concatenated with the name.
Define a method starts_with_consonant?(s) that takes a string and returns true if it starts with a consonant and false otherwise. (For our purposes, a consonant is any letter other than A, E, I, O, U.) NOTE: be sure it works for both upper and lower case and for nonletters!
Define a method binary_multiple_of_4?(s) that takes a string and returns true if the string represents a binary number that is a multiple of 4. NOTE: be sure it returns false if the string is not a valid binary number!
2、解决代码
#-------------------------------
#-----程序名称:homework for 02
#-----编译环境:ruby 2.2.3
#-----作 者:孙琨SealSun
#-----编写地点:UCAS
#-----编写时间:2015年10月05日
#--------------------------------
def hello(name)
# YOUR CODE HERE
puts "hello, "+name
end
def starts_with_consonant? s
# YOUR CODE HERE
reg_1=/[a-z]/
reg_2=/[^aeiou]/
if(reg_1===s[0].downcase && reg_2===s[0].downcase) #判断首位是否为不为元音的英语字母
return true
else
return false
end
end
def binary_multiple_of_4? s
# YOUR CODE HERE
reg=/[^01]/
if(reg===s) #判断其是否为二进制数
return false
elsif(s.to_i.to_s(10).to_i%4==0) #判断此二进制数是否能被4整除
return true
else
return false
end
end