红宝石并行作业,步骤问题 [英] ruby parallel assignment, step question

查看:140
本文介绍了红宝石并行作业,步骤问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在尝试通过做一些项目欧拉问题来学习红宝石,而我遇到了一些我无法解释的事情,而逗号呢?在两者中间.我还没有为此找到好的文档,也许我只是没有按照我的意愿使用google,但是好的ruby文档似乎有点稀疏. .

so, i'm trying to learn ruby by doing some project euler questions, and i've run into a couple things i can't explain, and the comma ?operator? is in the middle of both. i haven't been able to find good documentation for this, maybe i'm just not using the google as I should, but good ruby documentation seems a little sparse . . .

1:您如何描述它是如何工作的?第一个代码段是我不了解的Ruby代码,第二个代码段是我编写的仅在仔细跟踪第一个代码后才执行相同操作的代码:

1: how do you describe how this is working? the first snippet is the ruby code i don't understand, the second is the code i wrote that does the same thing only after painstakingly tracing the first:

#what is this doing?
cur, nxt = nxt, cur + nxt

#this, apparently, but how to describe the above?
nxt = cur + nxt   
cur = nxt - cur   

2:在下面的示例中,您如何描述带有"step"的行在做什么?从我可以收集到的信息来看,step命令的工作方式类似于(range).step(step_size),但这似乎在做(starting_point).step(ending_point,step_size).我对这个假设是正确的吗?在哪里可以找到好的文档?

2: in the following example, how do you describe what the line with 'step' is doing? from what i can gather, the step command works like (range).step(step_size), but this seems to be doing (starting_point).step(ending_point, step_size). Am i right with this assumption? where do i find good doc of this?

#/usr/share/doc/ruby1.9.1-examples/examples/sieve.rb  
# sieve of Eratosthenes
max = Integer(ARGV.shift || 100)
sieve = []
for i in 2 .. max
  sieve[i] = i
end

for i in 2 .. Math.sqrt(max)
  next unless sieve[i]
  (i*i).step(max, i) do |j|
    sieve[j] = nil
  end
end
puts sieve.compact.join(", ")

推荐答案

1:称为并行分配. Ruby会创建时间变量,而不用错误的值覆盖变量.所以这个例子:

1: It's called parallel assignment. Ruby cares to create temporal variables and not override your variables with incorrect values. So this example:

cur, nxt = nxt, cur + nxt

与以下相同:

tmp = cur + nxt
cur = nxt
nxt = tmp

bur更紧凑,没有地方犯愚蠢的错误等等.

bur more compact, without place to make stupid mistake and so on.

2:ruby核心库中有2个step方法.首先是Numeric类(每个数字),因此您可以编写:

2: There are 2 step methods in ruby core library. First is for Numeric class (every numbers), so you could write:

5.step(100, 2) {}

它从5开始并从中获取第二个数字,直到达到100.

and it starts at 5 and takes every second number from it, stops when reaches 100.

第二个step用于Range:

(5..100).step(2) {}

,它接受范围(具有开始和结束),并通过第二个元素遍历它.这是不同的,因为您可以传递的范围不一定是数字范围,它会占用第n个元素.

and it takes range (which has start and end) and iterates through it taking every second element. It is different, because you could pass it not necessarily numeric range and it will take every nth element from it.

看看 http://ruby-doc.org/core- 1.8.7/index.html

这篇关于红宝石并行作业,步骤问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆