To create a serial number array with characters in Ruby

Asked 2 years ago, Updated 2 years ago, 46 views

['a1', 'a2', 'a3', 'a4']

I'd like to make an array like this, but how can I do it?
Can't you do it like [*1..4] just like when you only do numbers or alphabets?

ruby

2022-09-30 20:59

4 Answers

I can pass the blocks to the Array constructor, so I think the most honest way to write them is as follows.

Array.new(4){|i|"a#{i+1}"}


2022-09-30 20:59

[*'a1'..'a4'].


2022-09-30 20:59

How about this one?

(1..20).map {|i|"a#{i}"}
=>["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13", "a14", "a15", "a16", "a17", "a19", "a20" ]

The rest is like this

['a'].product([*1..20]).map(&:join)
=>["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13", "a14", "a15", "a16", "a17", "a19", "a20" ]

It is probably impossible to write at a level like ['a'*1..4], and I think you need to combine several methods.


2022-09-30 20:59

Wouldn't it be better to implement a class that returns serial numbers with prefixes when you pass Range to the [] method?

class PrefixedSequence
  default (prefix)
    @prefix=prefix
  end

  def [ ] (range )
    range.map {|x|"#{@prefix}#{x}"}
  end
end

a_seq=PrefixedSequence.new(?a)

a_seq[1..10]


2022-09-30 20:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.