Ruby getting the longest word of a sentence
It depends on how you want to split the string. If you are happy with using a single space, than this works:
def longest(source)
arr = source.split(" ")
arr.sort! { |a, b| b.length <=> a.length }
arr[0]
end
Otherwise, use a regular expression to catch whitespace and puntuaction.
How to search for the longest word in the string
string.split(" ")
.max_by(&:length)
See Enumerable#max_by.
Ruby - Find the top 3 longest words in a string
>> str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
>> str.split.map { |s| s.gsub(/\W/, '') }.sort_by(&:length)[-3..-1]
=> ["adipisicing", "consectetur", "exercitation"]
Ruby Error with .length method
The issue is that you're iterating through the integers 0, 1, 2
when you pass "one three"
as your argument.
Unfortunately, you can't call the length
method directly on the integer/fixnum i
. Instead, you want to call it on the element at the index i
of the array sentence1
if that makes sense.
Something like this should work for you:
def longest_word(sentence)
sentence1 = sentence.split
longest_word = ""
for i in 0...(sentence1.length - 1)
if sentence1[i].length > longest_word.length
longest_word = sentence1[i]
end
end
return longest_word
end
Or, better yet
def longest_word(sentence)
sentence.split.max_by(&:length)
end
(Stolen from https://stackoverflow.com/a/21977468/716039)
Ruby longest word in array
I would do
class Array
def longest_word
group_by(&:size).max.last
end
end
how to break long text to smaller lines by words in ruby/rails?
Rails comes with the word_wrap
helper which can split long lines based on a given line width. It always splits at whitespace so long words won't get split / cut.
In rails/console
:
lines = helper.word_wrap("a b c d e text longword", line_width: 5)
#=> "a b c\nd e\ntext\nlongword"
puts lines
Output:
a b c
d e
text
longword
Note that it returns a string, not an array.
Ruby: Create function to find the word with most repeated letters
You have two problems:
counter
is not being updated.- Array#uniq returns
nil
if no change is made (as do many "bang" methods), raising the exception. Useuniq
.
This should work:
str = "one two three"
arr = str.split
counter = 0
most_repeat_letter_word = nil
arr.each do |w|
candidate = w.length - w.split('').uniq.length
if candidate > counter
most_repeat_letter_word = w
counter = candidate
end
end
puts most_repeat_letter_word
#=> three
Edit: Alas, I misread the question (even though I corrected the OP's stab), but I did answer another interesting question. squeeze
needs to be replace by uniq
above, as @DarkMouse did in his answer.]
You can use String#squeeze to advantage here, to remove duplicate repeated characters:
str = "Three blind mice, see how they run."
str.split.max_by { |w| w.size-w.downcase.squeeze.size }
#=> "Three"
Extract the last word in sentence/string?
This should work just fine
"my random sentence".split.last # => "sentence"
to exclude punctuation, delete
it
"my random sentence..,.!?".split.last.delete('.!?,') #=> "sentence"
To get the "last words" as an array from an array you collect
["random sentence...", "lorem ipsum!!!"].collect { |s| s.split.last.delete('.!?,') } # => ["sentence", "ipsum"]
Related Topics
How to Remove a Row from a CSV with Ruby
Read and Write File Atomically
Should I Be Using Rails or Ruby for This Website Application? How
How to Specify a Struct as the Return Value of a Function in Rubyffi
Google Analytics API Error "Selected Dimensions and Metrics Cannot Be Queried Together."
Why Does Ruby Hash a Fixnum N to 2N+1
Issues with Installing Ruby 2.0.0 on MACos Catalina
Why Does Ruby Release Memory Only Sometimes
How Would I Go About Converting This Time String to Epoch Time in Ruby
Authorizing Namespaced and Nested Controllers Using Cancan
Bundler Could Not Find Compatible Versions for Gem "Bundler": in Gemfile:
Encrypting/Decrypting 3Des in Ruby
Dynamically Create a Class Inherited from Activerecord
Using Watir to Check for Bad Links