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
目录
相关文章
|
前端开发 Android开发
Jetpack Compose 学习指南(二)
Jetpack Compose 学习指南(二)
163 0
|
6月前
|
网络协议 Python
Python3 notes
Python3 notes
|
算法 C语言 编译器
C语言实现粒子群算法(PSO)一
最近在温习C语言,看的书是《C primer Plus》,忽然想起来以前在参加数学建模的时候,用过的一些智能算法,比如遗传算法、粒子群算法、蚁群算法等等。当时是使用MATLAB来实现的,而且有些MATLAB自带了工具箱,当时有些只是利用工具箱求最优解问题,没有自己动手亲自去实现一遍,现在都忘的差不多了。
1957 0
|
5月前
|
SQL 机器学习/深度学习 分布式计算
MaxCompute产品使用问题之按量付费标准版和闲时版有什么区别
MaxCompute作为一款全面的大数据处理平台,广泛应用于各类大数据分析、数据挖掘、BI及机器学习场景。掌握其核心功能、熟练操作流程、遵循最佳实践,可以帮助用户高效、安全地管理和利用海量数据。以下是一个关于MaxCompute产品使用的合集,涵盖了其核心功能、应用场景、操作流程以及最佳实践等内容。
MaxCompute产品使用问题之按量付费标准版和闲时版有什么区别
|
Java 编译器 Go
终于弄懂Go语言变量逃逸分析 新手不能错过这篇指南
终于弄懂Go语言变量逃逸分析 新手不能错过这篇指南
209 0
|
存储 关系型数据库 MySQL
|
C++
C++学习002-C++代码中插入汇编语句
在C++中我们有时会遇到使用汇编语言的情况,这时可以在前面加上关键字“_asm”宏。
89 0
|
边缘计算 数据安全/隐私保护