Ruby Exercise

简介: Ruby Exercise1. Arrays, Hashes, and EnumerablesCheck the Ruby 2.

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
目录
相关文章
|
2月前
|
Python
“The Zen of Python” Easter Egg
“The Zen of Python” Easter Egg
50 2
|
前端开发 Android开发
Jetpack Compose 学习指南(二)
Jetpack Compose 学习指南(二)
174 0
|
7月前
|
存储 Shell iOS开发
【Python 学习篇】 Python环境变量设置指南 (A Guide to Setting Python Environment Variables)
【Python 学习篇】 Python环境变量设置指南 (A Guide to Setting Python Environment Variables)
797 1
|
7月前
|
SQL 关系型数据库 MySQL
Python3 notes
Python3 notes
|
算法 C语言 编译器
C语言实现粒子群算法(PSO)一
最近在温习C语言,看的书是《C primer Plus》,忽然想起来以前在参加数学建模的时候,用过的一些智能算法,比如遗传算法、粒子群算法、蚁群算法等等。当时是使用MATLAB来实现的,而且有些MATLAB自带了工具箱,当时有些只是利用工具箱求最优解问题,没有自己动手亲自去实现一遍,现在都忘的差不多了。
1965 0
|
API Python
Gevent----非官方的python协程库
Gevent----非官方的python协程库
107 0
|
Java 编译器 Go
终于弄懂Go语言变量逃逸分析 新手不能错过这篇指南
终于弄懂Go语言变量逃逸分析 新手不能错过这篇指南
230 0
React-52:setState的两种更新状态的方式
React-52:setState的两种更新状态的方式
125 0
React-52:setState的两种更新状态的方式
|
Java 索引
hashCode和equals的区别(一)
Hello,大家好,我是子悠,作为本周的小编我已经不想跟大家介绍自己了,这篇文章让我们跟随 Jay Pan( 哇,一位新作者哦)的步伐学习知识吧。下面是正文。 有面试官会问:你重写过 hashcode 和 equals 么,为什么重写equals时必须重写hashCode方法?equals和hashCode都是Object对象中的非final方法,它们设计的目的就是被用来覆盖(override)的,所以在程序设计中还是经常需要处理这两个方法。下面我们一起来看一下,它们到底有什么区别,总结一波!
|
C++
C++学习002-C++代码中插入汇编语句
在C++中我们有时会遇到使用汇编语言的情况,这时可以在前面加上关键字“_asm”宏。
93 0