Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
艰苦学习Ruby ex39:return-1,key,default_Ruby_Learn Ruby The Hard Way - Fatal编程技术网

艰苦学习Ruby ex39:return-1,key,default

艰苦学习Ruby ex39:return-1,key,default,ruby,learn-ruby-the-hard-way,Ruby,Learn Ruby The Hard Way,因此,我在做艰苦学习Ruby的练习,结果被卡在了一行上。尝试过谷歌搜索,甚至在Python课程中寻找答案。但是找不到答案 我的问题是:为什么Dict.get\u slot有这一行(它是干什么的?):返回-1,键,默认值 最初的练习如下: 谢谢大家 module Dict def Dict.new(num_buckets=256) # Initializes a Dict with the given number of buckets. aDict = [] (0...num_buc

因此,我在做艰苦学习Ruby的练习,结果被卡在了一行上。尝试过谷歌搜索,甚至在Python课程中寻找答案。但是找不到答案

我的问题是:为什么Dict.get\u slot有这一行(它是干什么的?):返回-1,键,默认值
最初的练习如下:

谢谢大家

module Dict
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

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

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

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

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

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

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.get_slot有这一行(它的作用是什么?):
return-1,key,default

这是一个返回三个值的数组的return语句。在执行return语句之前,ruby将替换变量key和default的值,然后ruby将这三个值收集到一个数组中并返回该数组。以下是一个例子:

def dostuff
  key = 'a'
  default = 10
  return -1, key, default
end

p dostuff

--output:--
[-1, "a", 10]
正如评论所说:

# Returns the index, key, and value of a slot found in a bucket.
评论回复:

Dict是一组数组,例如:

[
  [200, 'hello'], 
  [210, 'world'],
]
数组的第一个元素是实数键已转换为的整数,第二个元素是值

Dict.get_slot()有两个可能的返回值:

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

  return -1, key, default  #*****OR HERE****
如果在Dict中找到键,这意味着键等于子数组之一的第一个元素,则执行第一个return语句,并返回子数组的索引以及子数组的元素,即键和值。第二个return语句不执行

如果在Dict中找不到键,则跳过第一个return语句,并执行第二个return语句。在第二个return语句中,为子数组的索引返回-1。代码本来可以改为返回nil,但在其他语言中,当搜索未在数组中找到元素时,通常返回-1;从该方法的文档中可以看出,如果索引值为-1,则搜索结果为空。这些文件会说:

Dict.get_slot():返回一个三元素数组。第一个元素是 返回的数组是包含键的子数组的索引 或-1,如果没有子数组包含密钥

至于默认值,ruby哈希允许您指定在尝试检索不存在的密钥时返回的默认值(其他语言也提供该功能)。这使您可以执行以下操作:

h = Hash.new(0)
h['a'] = 1
h['b'] = 2

target_keys =  %w[a b c]  #=>['a', 'b', 'c']  For people who are too lazy to type all those quote marks.

sum = 0
target_keys.each do |target_key|
  sum += h[target_key]
end

puts sum  #=>3
如果无法指定默认值,则在哈希中查找不存在的密钥时将返回nil,结果如下:

`+': nil can't be coerced into Fixnum (TypeError)
这是因为代码试图将nil添加到总和中。当然,您可以通过在进行加法之前测试h[target_key]是否为nil来解决这个问题,但是能够指定默认值会使代码更加简洁

另一个更有用且非常常见的默认示例:

results = Hash.new { |this_hash, key| this_hash[key] = [] }

data = [
  ['a', 1],
  ['b', 2],
  ['a', 3],
  ['b', 4],
  ['c', 5],
]

data.each do |(key, val)|  #The parentheses cause the the subarray that is passed to the block to be exploded into its individual elements and assigned to the variables.
  results[key] << val
end

p results

--output:--
{"a"=>[1, 3], "b"=>[2, 4], "c"=>[5]}
results=Hash.new{| this_Hash,key | this_Hash[key]=[]
数据=[
[a',1],
[b',2],
[a',3],
[b',4],
[c',5],
]
data.each do |(key,val)|#括号使传递到块的子数组分解为其单独的元素并分配给变量。
结果[key][1,3],“b”=>[2,4],“c”=>[5]}
如果无法指定默认值,则以下行将导致错误:

results[key] << val

results[key]我就是不明白为什么会有-1和默认值。索引-1表示调用数组的最后一个元素,对吗?@abarro,请在我的回答中查看我对您评论的回应。