Seven weeks and seven languages: understanding a variety of programming patterns explain answers to Ruby exercises

Source: Internet
Author: User

This series is the answer to the exercises in "seven weeks and seven languages. This book does not stick to syntax details, but compares the programming paradigm between various programming languages (not popular) horizontally.

It is a good book that can help with programming awareness. I will not introduce it more here. If you are interested, please take a look.

I have to say that Ruby is a hacker.

1. Print the string "Hello, world ."

puts "Hello, world."

2. Find the subscript of "Ruby." In the string "Hello, Ruby.

puts "Hello, Ruby." =~ /Ruby/

3. print your name ten times

puts "angular "*10

4. Print the string "this is sentence number 1.", where the number 1 is always changed to 10.

i = 1..10i.each{|x| puts "This is sentence number #{x}.\n"}

5. Run the ruby program from the file

Create test1.rb

Write-> puts "Hello \ n"

Save and exit

Run-> Ruby test1.rb

6. Ask the player to guess the random number and tell the player whether the guess is big or small.

Guess. Rb

input = getsrNum = rand(10)if(input.to_i > rNum)  puts "bigger than #{rNum}"else  puts "not bigger than #{rNum}"end

7. Find the methods for reading files using code blocks and without code blocks respectively. What are the advantages of using code blocks?

File.open("test.rb") do |file|file.each_line{|line| puts "Got #{line.dump}"}end
File.open("test.rb").each{|f|puts "Got #{f}"}

You can use code blocks to pass Parameters and perform more operations.

8. How to convert a hash to an array

hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }

You can use collect/Map

hash.collect { |k, v| v }#returns [["a", "b", "c"], ["b", "c"]] 

You can also use values

hash.values

9. What data structures can be used for Ruby arrays as stacks?

It can be used as a queue, a linked list, a stack, a set, and so on.

10. There is an array containing 16 numbers. Only use the each method to print the content in the array, Print four numbers at a time, and then use the each_slice method of the enumeration module to re-do it.

myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]myArray.each do |a|  if a % 4 == 0    print "#{a}\n"  else    print "#{a} "  endend
require ‘enumerator‘myArray =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]myArray.each_slice(4) {|a| p a}

11. Write a TREE tree that can accept the hash and nested array Structures

12. Write a simple grep program to print out the row permissions of a phrase in the file. Add the row number.

puts "grep #{ARGV[0]};"File.open("e:/ruby/reg.txt") do |file|lnNum = 0  file.each_line do |ln|    lnNum +=1    p "Line:#{lnNum} =>  #{ln}" if ln =~ /#{ARGV[0]}/  endend

13. Modify the csv application to use the each method to return the csvrow object. Then, on the csvrow object, return the value of the column where the title is located using the method_missing Method for a given title.

For example, for files that contain the following content:

One, two

Lions, tigers

The API can be operated as follows:

CSV = rubycsv. New

CSV. Each (| row | puts row. One)

This prints "Lions"

module ActsAsCsv    def self.included(base)        base.extend ClassMethods    end    module ClassMethods        def acts_as_csv            include InstanceMethods        end    end    module InstanceMethods        def read            @csv_contents = []            filename = self.class.to_s.downcase + ‘.txt‘            file = File.new(filename)            @headers = file.gets.chomp.split(‘, ‘)            file.each do |row|                @csv_contents << row.chomp.split(‘, ‘)            end        end        def each            self.csv_contents.each do |row|                i = CsvRow.new(row)                yield i            end        end        attr_accessor :headers, :csv_contents        def initialize            read        end    endendclass CsvRow    def initialize(row)        @contents = row    end    def method_missing name, *args        num = name.to_s        if num == ‘one‘            @contents[0]        elsif num == ‘two‘            @contents[1]        end    endendclass RubyCsv    include ActsAsCsv    acts_as_csvendm = RubyCsv.newputs "Start...\n";m.each do |row| puts row.oneendputs "end...\n"

The csvrow class is customized, And the method_missing method of the class is rewritten, so that the default one/two method can be flexibly used as a parameter.

Summary:

Ruby's open classes and modules (programs that can write programs) allow programmers to add behavior to syntax, which is different from traditional class inheritance.

Seven weeks and seven languages: understanding a variety of programming patterns explain answers to Ruby exercises

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.