Ruby数组方法和输出 [英] Ruby arrays methods and outputs

查看:72
本文介绍了Ruby数组方法和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个数字,我的代码应返回1与该数字之间的所有偶数,并以以下格式打印它们:

Given a number, my code should return all the even numbers between 1 and the number, and print them in the following format:

22
4444
666666
etc...

这是到目前为止的代码:

This is the code so far:

def pattern(n)
  n == 1 ? "" : arr = (1..n).select {|i| i if i % 2 == 0}.each {|item| return (item.to_s * item)}
end

任何大于4的数字,只会返回以下内容:

With any number greater than four, it will only return the following:

22

我认为这可能与代码块中的return有关.但是,当使用printputs时,这将返回单个数组元素,如下所示:

I think that this may have something to do with the return in the block. However, when using print or puts, this returns an individual array element as follows:

[2]

是否有解决此问题的方法,以便我可以实现所需的输出?

Ideas for a way around this so that I can achieve the desired output?

推荐答案

此代码可解决您的问题:

This code fixes your issue:

def pattern(n)
  n == 1 ? "" : arr = (1..n).select {|i| i if i % 2 == 0}.map {|item| (item.to_s * item)}
end

请注意,我使用的是map而不是each,并且我没有使用return. return意味着您实际上并没有完成对数字的循环……从功能返回到2即可.

Note that I'm using map instead of each, and I'm not using a return. The return meant that you didn't actually finish looping over the numbers... as soon as you got to 2 you returned from the function.

map.

编辑

更多清理工作

def pattern(n)
  n == 1 ? "" : (1..n).select {|i| i.even?}.map {|item| item.to_s * item}
end

arr =是不必要的.您在select中的块应该只返回true或false ...您也可以在其中使用i % 2 == 0,但是even?恰好存在.另外,item.to_s * item周围的括号也是不必要的.

The arr = is unnecessary. Your block in a select should just return true or false... you could also use just i % 2 == 0 in there, but even? happens to exist. Also, the parentheses around item.to_s * item are unnecessary.

编辑2

根据下面的注释,如果您想要一个字符串,也许这就是您要查找的内容(添加了.join("\n")):

Per comments below, if you want a single string, maybe this is what you're looking for (added .join("\n")):

def pattern(n)
  n == 1 ? "" : (1..n).select {|i| i.even?}.map {|item| item.to_s * item}.join("\n")
end

编辑3

返回字符串时,也可以跳过n==1特殊情况,因为加入空数组只会返回一个空字符串:

When returning a string, you can also skip the n==1 special case, since joining an empty array will just return an empty string:

def pattern(n)
  (1..n).select {|i| i.even?}.map {|item| item.to_s * item}.join("\n")
end

这篇关于Ruby数组方法和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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