patternrubyMinor
Creating consecutive words from a string
Viewed 0 times
creatingwordsfromstringconsecutive
Problem
This is a method which creates an array of all possible consecutive substrings from a string:
To get a better idea I have added rspec for it:
How can this be made more idiomatic?
def get_seperated_tokens(query)
result = []
length = query.split.count
tokens = query.downcase.strip.split(' ')
length.times do |i|
length.times do |j|
result = i
end
end
result
endTo get a better idea I have added rspec for it:
describe "#get_seperated_tokens" do
it "returns an array of seperated tokens" do
query = 'ruby is awesome'
result = ['ruby','is', 'awesome', 'ruby is', 'is awesome','ruby is awesome']
expect(get_seperated_tokens(query)).to include(*result)
end
it "returns an array of seperated tokens" do
query = 'red blue iphones'
result = ['red','blue', 'iphones', 'red blue', 'blue iphones','red blue iphones']
expect(get_seperated_tokens(query)).to include(*result)
end
endHow can this be made more idiomatic?
Solution
As @Michael Szyndel mentioned in a comment,
Array#combination is the more appropriate method to use.def get_separated_tokens query
tokens = query.split
(0..tokens.size).to_a.combination(2).map{ |i,j| tokens[i...j].join " " }
endCode Snippets
def get_separated_tokens query
tokens = query.split
(0..tokens.size).to_a.combination(2).map{ |i,j| tokens[i...j].join " " }
endContext
StackExchange Code Review Q#28679, answer score: 2
Revisions (0)
No revisions yet.