Swap two strings 2 by 2 in ruby [closed] - ruby

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I've go a string made in this way.
"AABBCCDD....." grouped by 4 with variable lenght.
I need a method that swap that 2 by two the chars in this string
def swap2_by_2( string )
???
end
If the input is AABBCCDD the output will be BBAADDCC
Thanks, i'm very noob in ruby.
Edit: my mistake, a more comprhensive example may be.. Input: ABCDEFGH -> CDABGHEF

It is not clear what the OP is trying to do, but if it is to flip the first and the second characters with the third and fourth characters for every four characters, then the example that the OP showed is highly misleading and inappropriate (It should have been "ABCD..." instead of "AABB..."). In that case, a solution would be:
string.gsub(/(..)(..)/, '\2\1')

Thinking about your question, an interpreting the "ABCDEF", I am sure, that you are looking for pack / unpack in Ruby: I found a good page here How to change bit order in Ruby

And here are two a non-regexp versions:
p 'AABBCCDD'.chars
.each_slice(2)
.each_slice(2)
.map(&:reverse)
.join
#=> "BBAADDCC"
# or
'AABBCCDD'.chars
.each_slice(4)
.map{|x| x.rotate(2)}
.join

Related

How to best sort a list of strings with fractions in ruby? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Take an existing list of strings with whole and fractions of inch that includes the inch symbol:
['1"','1/2"','1 1/4"','1/4"','2"','1 1/8"']
Is there a best (rubyish, elegant, use of methods, object oriented) way in ruby to sort so it becomes
['1/4"','1/2"','1"','1 1/8"','1 1/4"','2"']
String#to_r will conveniently ignore trailing garbage (such as "):
The parser ignores leading whitespaces and trailing garbage.
so converting something like '1 1/2"' to a number that will compare sensibly is a simple matter of:
s = '1 1/2"'
r = s.split.map(&:to_r).inject(:+)
Split the string into pieces, convert each to a Rational using String#to_r, and then add them up using Enumerable#inject with a symbol argument. Clean and easy.
Once you have that, sorting is trivial:
array = ['1"','1/2"','1 1/4"','1/4"','2"','1 1/8"']
rationalized = lambda { |s| s.split.map(&:to_r).inject(:+) }
sorted = array.sort_by(&rationalized)
You don't have to use a lambda of course:
array.sort_by { |s| s.split.map(&:to_r).inject(:+) }
but I find that naming your little snippets of logic clarifies things.

How to get all decimal points in in ruby? ( HOLD) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The following shows that when I use the to_f method to covert a string to a floating point number and the last decimal point is dropped. How can preserve all decimal points in a given number?
irb(main):002:0> value='1.7.8'
=> "1.7.8"
irb(main):003:0> value.to_f
=> 1.7
Some context:
I am writing the the value to a file and If I write it as a string I get the quotes '1.7.8'. What I am looking for infact is 1.7.8. Hope that makes sense.
EDIT:
I see the error in my question so I'm trying to close it however I can only vote to close it.
just to clarify what I've found is actually contrary to what I said above.
turns out if I write the string '1.7' to a file it is written as '1.7' but with the string '1.7.8' it is written as 1.7.8. I'm just trying to understand why this is occurring.
To write it to a file simply write it like so:
value = "1.7.8"
File.open("file") { |f| f.puts("#{value}") }
The string in the file will not have quotes around it.

Issue with my Ruby Assignment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am new to learn Ruby, I got an assignment from my teacher which I am trying to understand.
Here is the question. Consider the following code:
ary = Array.new(7, "--day")
ary[2] = "Tuesday"
ary[4] = "Thursday"
ary[7] = "Sunday"
ary[-1] = "Saturday"
puts ary[7]
puts ary[-4]
puts ary[-6, 2]
puts ary[2] = ary[7][-3,3]
puts ary.length
Why does this code produce 6 lines of output? Where did the extra line come from?
What is the value of ary[2] at the end?
Why is the length (or size) of the array different than when we constructed it?
I won't answer these questions directly, since it sounds like it's a homework assignment, but I will try to point you in the right direction.
Take a look at the documentation for Ruby's Array#[]. More specifically, take a look at which usages in your example code match the usages in the examples, and you might get a better idea of what's happening. Keep in mind that with Ruby, you can index from the end of your array by using negative index numbers.
Open up irb in the terminal and run the first 5 lines (all the ary[]= lines). Then run each of the puts lines individually and see what the output is. Keep in mind that lines with => something are the return values, not what is being printed.
Take a look at String#[], and try out the different parts of line 9 individually. For example, see what ary[7] does. Then see what ary[7][-3, 3] does. See what happens if you do "Any Random String"[a_number, another_number].
After you first create the array, check ary.length. Then run each of the following lines, checking ary.length after each subsequent assignment.
Don't get discouraged, and don't listen to people telling you to give up. This stuff can be confusing when you first start out, but getting familiar with where to find documentation, how to use the command line tools, and how to experiment will make it much easier to explore and discover what your code is doing, when, and why.
If you ever need to try and figure out what is going on in your code, just open up irb in your terminal and start playing around with it, and you should be able to answer most of your questions through experimentation.

< > inside a Ruby String [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I was reading something else posted by a user on here explaining how yield statements work in Ruby. Part of the code he was using was :
print_list( [1,2,3], 23 ) { |n| "<#{n}>"}
what do the < > mean inside the string? It's such a simple question but I haven't been able to find out the answer to it.
In a string literal neither < nor > have any implied meaning - although such might have meaning in the output or use of the resulting string.
Only escape sequences and # (in interpolated literals) have intrinsic meaning.
These characters are just a part of string.
And any character which lies inside #{ } will be evaluated, which is also referred to Interpolation

How to check if a character appears in a string exactly one time or multiple times? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
So say I have three strings. I am trying to check if the letters in two appear EXACTLY ONCE in "doopdedoo", and if the letters in three appear an unlimited amount of times.
one = "doopdedoo"
two = "dp"
three = "o"
if one.{|a| a.chars.all? {|c| "#{three}".include?(c)}} && one.{|a| a.chars.once? {|c| "#{two}".include?(c)}}
I have used the above to test for the presence of an unlimited amount of o's. How to test for a limited amount of d's and p's?
Edit:
Sorry but I need to clarify. My expected output would be nothing for this case.
[]
Because doopdeedoo contains more than one instance of d or p.
It does contain many o's, so that's fine.
I also added the &&... part to the method above. I realize there is no 'once' method but if there is something like that I'd like to use it.
You can use the String#count method like this:
test_string = "foopaad"
must_appear_once = ['d', 'p']
must_appear = ['o']
must_appear_once.all? {|c| test_string.count(c) == 1} \
and must_appear.all? {|c| test_string.count(c) > 0}
This ensures that 'd' and 'p' each appear exacly once and that 'o' appears in the string (no matter how often).

Resources