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
目录
相关文章
|
11天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1230 5
|
10天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1213 87
|
10天前
|
云栖大会
阿里云云栖大会2025年9月24日开启,免费申请大会门票,速度领取~
2025云栖大会将于9月24-26日举行,官网免费预约畅享票,审核后短信通知,持证件入场
1796 13
|
20天前
|
人工智能 运维 安全
|
3天前
|
资源调度
除了nrm-pm,还有哪些工具可以管理多个包管理器的源?
除了nrm-pm,还有哪些工具可以管理多个包管理器的源?
234 127
|
4天前
|
前端开发
Promise的then方法返回的新Promise对象有什么特点?
Promise的then方法返回的新Promise对象有什么特点?
177 2