Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a range of strings from end values

Tags:

range

ruby

I use irb.

I write the code below.
"ax".."bc"
I expect
"ax""ay""az""ba"bb""bc"

But the result is just
"ax".."bc"

How should I correct? Thanks.

like image 988
Kotaro Ezawa Avatar asked Sep 30 '11 23:09

Kotaro Ezawa


3 Answers

> puts ("ax".."bc").to_a
ax
ay
az
ba
bb
bc
like image 53
Mark Byers Avatar answered Sep 18 '22 11:09

Mark Byers


The range 'ax' .. 'bc' does represent the values that you expect but it doesn't generate them until it really needs to (as a way to save time and space in case you don't end up using each value). You can access them all via an interator or conversion to an array:

r = 'ax' .. 'bc' # => "ax" .. "bc"
r.class # => Range
r.to_a # => ["ax", "ay", "az", "ba", "bb", "bc"]
r.to_a.class # => Array
r.each {|x| puts x}
ax
ay
az
ba
bb
bc
like image 35
maerics Avatar answered Sep 18 '22 11:09

maerics


Range is a builtin in construct, internally storing start and ending point (and whether it's an end-inclusive range) for efficiency. So IRB will just show you the literal for it.

What do you want to do?

like image 37
Karoly Horvath Avatar answered Sep 18 '22 11:09

Karoly Horvath