Ruby Exercise

Ruby Exercise

1. Arrays, Hashes, and Enumerables

Check the Ruby 2.x documentation on Array, Hash and Enumerable as they could help tremendously with these exercises.

  • Define a method sum(array) that takes an array of integers as an argument and returns the sum of its elements. For an empty array it should return zero.
def sum arr
         i=0
         sum=0
         until i==arr.length do
               sum+=arr[i]
               i=i+1
         end
         return  sum
end
  • Define a method max_2_sum(array) which takes an array of integers as an argument and returns the sum of its two largest elements. For an empty array it should return zero. For an array with just one element, it should return that element.
def max_2_sum arr
      i=0
        sum=0
         if arr.length==0
              sum=0
         elsif arr.length==1
              sum=arr[0]

         elsif arr.length==2
               sum=arr[0]+arr[1]          
         else              
               sum=arr.max
               max_index=arr.index(sum)
               arr.delete_at(max_index)
               sum+=arr.max
       end
       return sum
end
  • Define a method sum_to_n?(array) that takes an array of integers and an additional integer, n, as arguments and returns true if any two elements in the array of integers sum to n. An empty array should sum to zero by definition.
def sum_to_n? arr, n
       len=arr.length
       if(len==0&&n==0) then return false end

       i=0
       while i<len
          j=i+1
          while j<len
            if(arr[i]+arr[j]==n)  then  return true end
            j=j+1
          end
          i=i+1
       end    
        return false
end

2. Strings and Regular Expressions

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.
def hello(name)
  return "Hello, "+name;
end
  • 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!
def starts_with_consonant? s
    if s.empty? then return false end
      if (s[0,1]=~/^[aeiou]/||s[0,1]=~/^[AEIOU]/) then return false;                 
        end
    if !(s[0,1]=~/[a-zA-Z]/)
        return false
    end
        return true;    
end
  • 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!
def binary_multiple_of_4? s
    if  s=~/^[01]0*1*/ then  
         s="0b"+s                         #二进制字符串加上0b   
         s=Integer(s)                     #字符串转为整数
         if s%4==0 then return true end
           #是4的倍数返回true  
    end

    return false
end

3. Object Oriented Basics

Define a class BookInStock which represents a book with an ISBN number, isbn, and price of the book as a floating-point number, price, as attributes.

The constructor should accept the ISBN number (a string, since in real life ISBN numbers can begin with zero and can include hyphens) as the first argument and price as second argument, and should raise ArgumentError (one of Ruby’s built-in exception types) if the ISBN number is the empty string or if the price is less than or equal to zero. Include the proper getters and setters for these attributes.

Include a method price_as_string that returns the price of the book formatted with a leading dollar sign and two decimal places, that is, a price of 20 should format as “20.00"andapriceof33.8shouldformatas"33.80”.

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
上一篇:[前端]JS时钟实例


下一篇:[数据结构]基本概念、单链表操作