Ruby第一次作业解答

作者: 云中布衣   分类:  数据比赛    热度: (731℃)   时间: 2015-10-8 2:17   标签: #作业  #ruby  #高级软件工程    
#author:Wenyan Yu
#institute:Computer and Control
#class:710
#student ID:2015E8007361074
#personal website:www.mryu.top

#Part1
def sum arr
	sum_arr=0
	if arr.length==0
		return sum_arr
	else
		for i in 0...arr.length
		sum_arr+=arr[i] 
		end#for
	end#if
	return sum_arr#返回数组所有元素之和
end

def max_2_sum arr

	if arr.length==0
		return 0#若数组为空,则返回0
	elsif arr.length==1
		return arr[0]#若数组只有一个元素,则返回这个元素
	else
		large1=arr[0]
		large2=arr[1]
		if large1<large2 then large1,large2 = large2,large1 end

		for i in 2...arr.length
		 	if arr[i]>large2 then large2=arr[i] end
			if large1<large2 then large1,large2 = large2,large1 end
		end#for
		return large1+large2#若数组有多余一个元素,则返回它最大的两个元素之和	
	end#if

end

def sum_to_n? arr,n
	
	
	if arr.empty?
		return false if n==0
	else 
		for i in 0...arr.length 
			for j in (i+1)...arr.length
				return true if arr[i]+arr[j]==n
			end#for 内
		end#for 外
		
	end#if
	return false	
end

#Part 2

def hello(name)
	return "Hello, "+name
end

def starts_with_consonant? s
		str="AEIOU"
		str1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		s=s.upcase#将字符串全部转换为大写		
		flag=false#s是以辅音字母开头则flag置为true,否则置为false
		#puts str !~ /B/
		#puts str1 =~ /B/
		#if str1 =~ /B/ and str !~ /B/ then flag=true end
		if str1.include?s[0,1] and !str.include?s[0,1] then flag=true end#如果s的首字母是辅音字母则将flag置为true
		return flag
end

def binary_multiple_of_4? s

	#	if s =~ /^[0-1]+$/
    	#	  return s.to_i(2) % 4 == 0 unless s == "0"
  	#	end

  	#	return false
	

	 	
	#return  s=~ /^[01]*1[01]*00$/ 
	if s.empty?
		return false
	end
	for i in 0...s.length
		if s[i] < "0" || s[i] > "2"
			return false
		end        
	
	end
		
	if s.to_i % 4==0
		return true
	else 
		return false
	end
	
	
	
	
	
	
end


#Part 3

class BookInStock

	def initialize(isbn,price)
		raise ArgumentError if isbn.empty? || price <= 0	
		@isbn=isbn
		@price=price
	end#初始化方法结束
	
	def price_as_string
		format("$%.2f",@price)
	end#方法结束
	attr_accessor:isbn
	attr_accessor:price
	
end	

56.8K

发表评论:

© 云中布衣 2015 | Driven by EMLOG  | SiteMap | RunTime: 10.87ms&RSS  | MORE  |   | TOP

文章数量【258】 评论数量【238】 稳定运行【1211天】

Visitor IP Address【54.92.193.89】

Email:ieeflsyu#outlook.com