1

Trying to do something like:

def action(number)

nums = [1...number]
code_here...

end

Do I need to write up a "count" snippet for this to work? Or is something similar to what I'm trying to do possible?

2
  • "that counts to a given value" sounds more like a loop or maybe a method that yields those values. Commented Jan 26, 2021 at 19:06
  • @Stefan It does, and I'd be able to do it in a loop, but I'm just trying to declare a variable whose value is the number and all the numbers before it starting at 1. Felt declaring it as an array off rip, as opposed to looping for those values and then pushing them into an array, would result in a faster log time. It's for leetcode and I like seeing "100%" on speed, though sometimes that means coming up with "hacky" solutions. Commented Jan 27, 2021 at 20:17

2 Answers 2

4

There's another option to use enumerators:

1.upto(10).to_a #=> [1,2,3,4,5,6,7,8,9,10]

There are quite a few useful ones. For example, if you only need every other number up to certain number you can use:

0.step(100, 2).to_a #=> [0,2,4,6,8,..., 98,100]

Another option would be to use Array constructor:

Array.new(10) { |i| i + 1 } #=> [1,2,3,4,5,6,7,8,9,10]

which is a bit more verbose, but gives you much more freedom:

Array.new(10) { |i| 2 ** i } #=> [1,2,4,8,16,32,64,256,512]
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, bro, long time no see. Still banging away on that piano, eh? How about something to represent the weird category, like (1...).first(10)?
@CarySwoveland weird it is Enumerator.produce(1,&:succ) (less than 2.7 Enumerator.new {|y| i = 0; loop {y << i+=1}})
@engineersmnky, maybe add .first(10).
1.step.take(10) is another option
3

There are two solutions for this as following:

If you want to add number in the array than:

nums = [*1..number]
# or
nums = (1..number).to_a

Ignoring last number than:

nums = [*1...number]
# or
nums = (1...number).to_a

2 Comments

It actually kinda hurts to be this close yet completely miss the target.
Well maybe a few more than 2 options 1.upto(number) or Array.new(number) {|i| i + 1} or to start at 0 number.times or Array.new(number).each_index etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.