添加断言功能

时间:2015-03-01 16:48:35

标签: ruby-on-rails ruby

我是Ruby on Rails的新手,现在正在学习Ruby Ruby the Hard Way。在本课中,我应该将Assert功能添加到Dict.rb(如下所示)。有谁知道我怎么能这样做?我每次尝试都会收到错误。

module Dict

    #Creates a new function that makes a Dictionary. This is done through creating the 
    # aDict variable that has an array in which num_buckets array is placed inside.
    # These buckets will be used to hold the contents of the Dict and later aDict.length
    # is used to find out how many buckets there are.  
    def Dict.new(num_buckets=256)
        # Initializes a Dict with the given number of buckets.
        aDict = []
        (0...num_buckets).each do |i|
            aDict.push([])
        end

        return aDict
    end

    # Converts a string to a number using the bult-in Ruby 'hash' function
    # Once I have a number for the key, I use the % operator and aDict.length to get a 
    # bucket where the remainder can go. 
    def Dict.hash_key(aDict, key)
        # Given a key this will create a number and then convert it to an index for the
        # aDict's buckets
        return key.hash % aDict.length
    end

    # Uses hash_key to find a bucket that the key could be in. Using bucket_id I can get 
    # the bucket where the key could be. By using the modulus operator I know it will fit
    # into the aDict array of 256.
    def Dict.get_bucket(aDict, key)
        # Given a key, find the bucket where it would go.
        bucket_id = Dict.hash_key(aDict, key)
        return aDict[bucket_id]
    end

    # Uses get_slot to get the (i, k, v) and returns the v (value) only. 
    def Dict.get_slot(aDict, key, default=nil)
        # Returns the index, key and value of a slot found in a bucket.
        bucket = Dict.get_bucket(aDict, key)

        bucket.each_with_index do |kv, i|
         k, v = kv
         if key == k
            return i, k, v
         end
        end

        return -1, key, default
    end

    def Dict.get(aDict, key, default=nil)
        # Gets the value in a bucket for the given key or the default.
        i, k, v = Dict.get_slot(aDict, key, default=default)
        return v
    end

    # Sets a key/value pair by getting the bucket and appending the new (key, value) to it.
    # First you have to get the bucket, see if the key already exists, if it does then
    # replace it, if it doesn't get replaced then append it. 
    def Dict.set(aDict, key, value)
        # Sets the key to the value, replacing any existing value.
        bucket = Dict.get_bucket(aDict, key)
        i, k, v = Dict.get_slot(aDict, key)

        if i >= 0
            bucket[i] = [key, value]
        else
            bucket.push([key, value])
        end
    end

    # Deletes a key by getting the bucket, searching for key in it and deleting it form the
    # array. 
    def Dict.delete(aDict, key)
        # Deletes the given key from the Dict.
        bucket = Dict.get_bucket(aDict, key)

        (0...bucket.length).each do |i|
            k, v = bucket[i]
            if key == k
                bucket.delete_at(i)
                break
            end
        end
    end

    # goes through each slot in each bucket and prints out what's in the Dict. 
    def Dict.list(aDict)
        # Prints out what's in the Dict.
        aDict.each do |bucket|
            if bucket
                bucket.each {|k, v| puts k, v}
            end
        end
    end
end

我使用以下脚本从模块Dict.rb运行方法:

require './dict.rb'

# create a mapping of state to abbreviation
states = Dict.new()
Dict.set(states, 'Oregon', 'OR')
Dict.set(states, 'Florida', 'FL')
Dict.set(states, 'California', 'CA')
Dict.set(states, 'New York', 'NY')
Dict.set(states, 'Michigan', 'MI')

# create a basic set of states and some cities in them
cities = Dict.new()
Dict.set(cities, 'CA', 'San Francisco')
Dict.set(cities, 'MI', 'Detroit')
Dict.set(cities, 'FL', 'Jacksonville')

# add some more cities
Dict.set(cities, 'NY', 'New York')
Dict.set(cities, 'OR', 'Portland')

# puts out some cities
puts '-' * 10
puts "NY State has: #{Dict.get(cities, 'NY')}"
puts "OR State has: #{Dict.get(cities, 'OR')}"

# puts some states
puts '-' * 10
puts "Michigan's abbreviation is: #{Dict.get(states, 'Michigan')}"
puts "Florida's abbreviation is: #{Dict.get(states, 'Florida')}"

# do it by using the state then cities dict
puts '-' * 10
puts "Michigan has: #{Dict.get(cities, Dict.get(states, 'Michigan'))}"
puts "Florida has: #{Dict.get(cities, Dict.get(states, 'Florida'))}"

# puts every state abbreviation
puts '-' * 10
Dict.list(states)

# puts every city in state
puts '-' * 10
Dict.list(cities)

puts '-' * 10
# by default ruby says "nil" when something isn't in there
state = Dict.get(states, 'Texas')

if !state
    puts "Sorry, no Texas."
end

# default values using ||= with the nil result
city = Dict.get(cities, 'TX', 'Does Not Exist')
puts "The city for the state 'TX' is: #{city}"

1 个答案:

答案 0 :(得分:1)

Ruby中默认没有“assert”方法。这就是为什么你得到一个“未定义的方法”错误。您需要自己实现此方法或使用MinitestRspec等测试框架。

如果你想自己实现一个简单的断言方法,那就是这样的:

def assert(first_item, second_item)
  unless first_item == second_item
    puts "[Error] #{first_item} does not equal #{second_item}"
  end
end

然后像这样使用它:

assert(Dict.get(cities, 'NY'), 'New York')

这个想法是断言可以帮助您确保代码返回预期的输出,而无需手动检查。