长循环与短循环Ruby

时间:2016-04-05 01:03:53

标签: ruby loops

使用下面的代码作为示例,有人可以给我一个循环方法的单行代码示例并向我解释差异吗?我知道有一个短循环版本和一个循环版本,我认为这对社区搜索(以及我自己的理解)很有帮助。

def first_square_numbers(number_of_squares)
  squares = []

  idx = 0
   while idx < number_of_squares
   squares.push(idx * idx)
    idx = idx + 1
  end

  return squares
end

3 个答案:

答案 0 :(得分:5)

def f x
  (0...x).map { |n| n * n }
end

答案 1 :(得分:5)

您可以使用cols = [] joins = [] insp = inspection.inspect(DNAExtractionProtocol) for name, col in insp.columns.items(): cols.append(col.label(name)) for name, rel in insp.relationships.items(): alias = aliased(rel.mapper.class_, name=name) joins.append((alias, rel.class_attribute)) for col_name, col in inspection.inspect(rel.mapper).columns.items(): #the id column causes double entries, as it is mapped once on the parent table (related_table_id) and once on the child table (table_id) if col.key != "id": aliased_col = getattr(alias, col.key) cols.append(aliased_col.label("{}_{}".format(name, col_name))) sub_insp = inspection.inspect(rel.mapper.class_) for sub_name, sub_rel in sub_insp.relationships.items(): if "contains" not in sub_name: sub_alias = aliased(sub_rel.mapper.class_, name=name+"_"+sub_name) joins.append((sub_alias, sub_rel.class_attribute)) for sub_col_name, sub_col in inspection.inspect(sub_rel.mapper).columns.items(): print(sub_alias, sub_col.key, '###') #the id column causes double entries, as it is mapped once on the parent table (related_table_id) and once on the child table (table_id) if sub_col.key != "id": sub_aliased_col = getattr(sub_alias, sub_col.key) cols.append(sub_aliased_col.label("{}_{}_{}".format(name, sub_name, sub_col_name))) sql_query = session.query(*cols).select_from(DNAExtractionProtocol) for join in joins: sql_query = sql_query.outerjoin(*join) sql_query = sql_query.filter(DNAExtractionProtocol.code == code) 构造函数的块功能:

Array

这将创建所需大小的数组,然后应用提供的块来评估指定的每个索引位置def first_square_numbers(number_of_squares) Array.new(number_of_squares) { |i| i * i } end ,在这种情况下,对索引值进行平方。有关详细信息,请参阅Array docs

答案 2 :(得分:0)

我认为这适用于阻止而不是循环。循环结构通常传递一个块(循环执行)。区别在于使用一组花括号{}do ... end关键字块。语法差异专门针对适合一行和多行bbatsov/ruby-style-guide的代码。

循环需要一个结束语句,所以没有&#34;短&#34;它们的版本,包括do关键字或不包含。

for x in (0...5)
  p x
end

for x in (0...5) do
  p x
end