Reverse a string each two characters with Ruby
I'm not sure if this is the best way to do it:
"0123456789abcdef".scan(/../).reverse.join == "efcdab8967452301"
Ruby reverse string with unshift
split
isn't doing what you think it is (by default, it splits on whitespace, not on each character):
> "Hello".split
#=> ["Hello"]
You probably want chars
:
> "Hello".chars
#=> ["H", "e", "l", "l", "o"]
You can also just use the each_char
method:
string.each_char do |char|
Method to reverse string only if it has less than four letters
just put puts conditional_reverse("cat")
out side our def
def conditional_reverse(string)
good = string.length
if good < 4
puts string.reverse
else
puts string
end
end
conditional_reverse("cat")
Related Topics
Getting a Rogue Iteration from My .Each Loop
Instance_Eval Does Not Work with Do/End Block, Only with {}-Blocks
Can't Dup Nilclass on Association Methods
Bootstrap Modal in Ruby on Rails Not Working
Ruby Parenthesis Syntax Exception with I++ ++I
Using Poltergeist with a Proxy
How to 'Join' an Array Adding to the Beginning of the Resulting String the First Character to Join
Ruby Facebook Graph API Appsecret_Proof
How to Understand the #Dup and #Clone Operate on Objects Which Referencing Other Objects
Rails 404 Error for Stylesheet or JavaScript Files
Calling Instance Variables Without @
Stubbing Controller Actions in Rspec Request Specs
Ruby's "Foo = True If !Defined? Foo" Won't Work as Expected
Getting Rails to Accept European Date Format (Dd/Mm/Yyyy)
How to Create a "Clone"-Able Enumerator for External Iteration
Openssl::Ssl::Sslcontext Sni Servername_Cb Not Working
Why Is Heroku's Heroku-18 Stack Only Compatible with Puma Versions 3.7.X