Cycle single character in a word

Hello everyone, I’m trying to generate words with a single character in it cycling but i’m new to programming so I really don’t how to do this.
I tried this but i always get errors :
a = [‘ABCDEF’]
a[0].cycle { |x| puts x }

I’m expecting an output like this (example ):
ABCDEF
BBCDEF
CBCDEF
DBCDEF
…etc

Can someone help me on this ?

You have as an array with a single value which is a string ‘ABCDEF’. Then you are calling cycle on the first element of the array, that string, not the array itself. Since cycle is an enumerable method (for things like arrays and hashes, that you iterate through), it will return an error when you run it on a string. To run it on the array you created you would call a.cycle. That will resolve the error, but it still won’t give you the results you want, since cycle just loops through and outputs each element of the array. Based on your example, cycle isn’t necessarily what you want to use.

Your example doesn’t give the best example of what your overall goal, but maybe this will help.
You can either change your variable to be an ARRAY of letters or a STRING

an array

a = ['A', 'B', 'C', 'D', 'E', 'F']
a.each { |x| puts [x, a.values_at(1..)].join() }

each iterates over the array
values_at returns the array starting at the second element to the end
join turns the array back into a string

a string

a = 'ABCDEF'
a.chars { |x| puts [x, a.chars.values_at(1..)].join() }

chars turns the string into an array of characters like the example of above

Both of those will return the example you shared.

Another Example

abc = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"].
word = "BAT"
abc.each { |x| puts [x, word.chars.values_at(1..)].join() }

AAT
BAT
CAT
DAT
EAT
FAT
GAT
HAT
IAT
JAT
KAT
LAT
MAT
NAT
OAT
PAT
QAT
RAT
SAT
TAT
UAT
VAT
WAT
XAT
YAT
ZAT

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

Sponsor our Newsletter | Privacy Policy | Terms of Service