['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?
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}"}
[*'a1'..'a4']
.
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.
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]
© 2024 OneMinuteCode. All rights reserved.