HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Creating consecutive words from a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creatingwordsfromstringconsecutive

Problem

This is a method which creates an array of all possible consecutive substrings from a string:

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
end


To 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
end


How 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 " " }
end

Code Snippets

def get_separated_tokens query
  tokens = query.split
  (0..tokens.size).to_a.combination(2).map{ |i,j| tokens[i...j].join " " }
end

Context

StackExchange Code Review Q#28679, answer score: 2

Revisions (0)

No revisions yet.