class Hello
def self.best_sentence(sentences,desired_words)
ranked_sentences = sentences.sort_by do |s|
s.words.length - (s.downcase.words - desired_words).length
end
ranked_sentences.last
end
def words
scan(/\w[\w’-]*/)
end
end
puts Hello.best_sentence("[This is a test, This is a ruby
test]",%q{ruby test})
The error always prompting me an undefined method `sort_by’ for “[This
is a test, This is a ruby test]”:String (NoMethodError)
this is because Array#sort_by is undefined. Which means there is no
method sort_by in the Array class. You can check this by looking at the
documentation for Array:
There is however, a method Array#sort_by! (The exclamation mark is
important.) The exclamation mark means (by convention) that a method
changes the state of the object, which is another way of saying that it
changes the values of (at least) one of the object’s variables.
this is because Array#sort_by is undefined. Which means there is no
method sort_by in the Array class. You can check this by looking at the
documentation for Array:
There is however, a method Array#sort_by! (The exclamation mark is
important.) The exclamation mark means (by convention) that a method
changes the state of the object, which is another way of saying that it
changes the values of (at least) one of the object’s variables.
sort_by comes from Enumerable, but that has nothing to do
with the problem at hand.
The problem is actually given in the error message:
undefined method `sort_by’ for “[This is a test, This is a ruby
test]”:String (NoMethodError)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
this is because Array#sort_by is undefined. Which means there is no
method sort_by in the Array class. You can check this by looking at the
documentation for Array:
There is however, a method Array#sort_by! (The exclamation mark is
important.) The exclamation mark means (by convention) that a method
changes the state of the object, which is another way of saying that it
changes the values of (at least) one of the object’s variables.
sort_by comes from Enumerable, but that has nothing to do
with the problem at hand.
The problem is actually given in the error message:
undefined method `sort_by’ for “[This is a test, This is a ruby
test]”:String (NoMethodError)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
undefined method `words’ for “I like ruby”:String (NoMethodError)
which i place the method words inside the Hello class
Well - if the method words() resides in class Hello, then it is
not available on class String.
You need to make sure to call .words() only on objects of class
Hello then - have a look why you have a String object when you
instead expect a Hello object.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.