Convert a letter to its corresponding control code - ruby

Given a single letter (string), say "a", I want to convert this into its corresponding control code, i.e. "\ca" - or equivalently (in alternate syntax) - "\C-a", ?\ca, "\x01", "\u0001"
I was hoping there'd be some "nice", clean way of doing this conversion, but I can't figure it out.
An obvious first attempt might be to try something like:
def convert_to_control_code(letter)
"\c#{letter}"
end
...But this does not work, since this will always return "\u0003{letter}" (where "\u0003" is the control code "\c#"
My current solution is simply to "brute force" it by doing the following:
def convert_to_control_code(letter)
(0..255).detect { |x| x.chr =~ Regexp.new("\\c#{char}") }.chr
end
However, I can't help but feel there's a "right" way of doing this!
Edit:
Here's another, non brute-force solution I've come up with, that seems to work:
def convert_to_control_code(letter)
(letter.ord % 32).chr
end
This looks much nicer, but also very hacky!

You can write it as :
def convert_to_control_code(letter)
eval "?\\C-#{letter.chr}"
end
convert_to_control_code(97) # => "\u0001"
convert_to_control_code(98) # => "\u0002"

One possibility is to do the same as Ruby itself does. It might look something like this:
def convert_to_control(letter)
letter = letter.chr # ensure we are only dealing with a single char
return 0177.chr if letter == '?'
raise 'an error' unless letter.ascii_only? # or do something else
(letter.ord & 0x9f).chr
end
You might want to change the encoding of the result depending on what you are doing.

Related

Detecting a missing sub!, sort!, map!, etc

After returning to Ruby from a long stint coding in another language, I regularly assume that foo.sort, foo.map {...}, foo.sub /bar/, 'zip' will change foo. Of course I meant foo.sort!, etc. But that usually takes 3 or 4 debugging potshots before I notice. Meanwhile, the sort is calculated, but then isn't assigned to anything. Can I make ruby warn about that missing lvalue, like a C compiler warns of a function's ignored return value?
You mean like Perl's somewhat infamous "using map in void context"? I don't know of Ruby having such a thing. Sounds like you need more unit testing to catch mistakes like this before they can worm into your code deeply enough to be considered bugs.
Keep in mind Ruby's a lot more flexible than languages like Perl. For example, the following code might be useful:
def rewrite(list)
list.map do |row|
row += '!'
end
end
Now technically that's a map in a void context, but because it's used as a return value it might be captured elsewhere. It's the responsibility of the caller to make use of it. Flagging the method itself for some sort of warning is a level removed from what most linting type tools can do.
Here's a very basic parser :
#forgetful_methods = %w(sort map sub)
Dir['*.rb'].each do |script|
File.readlines(script).each.with_index(1) do |line, i|
#forgetful_methods.each do |method|
if line =~ /\.#{method}(?!!)/ && $` !~ /(=|\b(puts|print|return)\b|^#)/
puts format('%-25s (%3d) : %s', script, i, line.strip)
end
end
end
end
# =>
# brace_globbing.rb ( 13) : subpatterns.map{|subpattern| explode_extglob(match.pre_match+subpattern+match.post_match)}.flatten
# delegate.rb ( 11) : #targets.map { |t| t.send(m, *args) }
It checks every ruby script in the current directory for sort, map or sub without ! that aren't preceded by =, puts, print or return.
It's just a start, but maybe it could help you find some of the low hanging fruits.
There are many false positives, though.
A more complex version could use abstract syntax trees, for example with Ripper.

Ruby - Populate and Array with returned method values

So, pretend we have the following three methods that check a grid to determine if there is a winner, and will return true if there is.
def win_diagonal?
# Code here to check for diagonal win.
end
def win_horizontal?
# Code here to check for horizontal win.
end
def win_vertical?
# Code here to check for vertical win.
end
I would like to push the returned values of each method into an Array instead of literally using the method names. Is this possible?
def game_status
check_wins = [win_vertical?, win_diagonal?, win_horizontal?]
if check_wins.uniq.length != 1 # When we don't have only false returns from methods
return :game_over
end
end
What you are looking for will indeed work in ruby.
def hello_world?
"hello world!"
end
a = [hello_world?]
Prints out
=> ["hello world!"]
Hope that helps. IRB is your friend when you wonder if something is possible in Ruby :-)
Simpler way (and very readable) yet:
def game_status
win_vertical? || win_diagonal? || win_horizontal?
end
If, for example, win_vertical? returns true, the other algorithms won't even need to run. You return immediately.
Or, if you need to know in which way the user won, I mean, if you need to preserve the results of all methods after they ran, you can use a hash, like:
{:vertical => win_vertical?, :diagonal => win_diagonal?, :horizontal => win_horizontal?}
This solution, like the array one, is worse than the first one above for it runs all algorithms all the time. If they are complex, you may have a problem. =)
You can do something like this when you really want to store all return values in an array:
def game_status
check_wins = [win_vertical?, win_diagonal?, win_horizontal?]
return :game_over if check_wins.any?
end
For readability I would prefer:
def game_status
return :game_over if win_vertical? || win_diagonal? || win_horizontal?
end

Ruby refactoring sentence manipulation

I have a bit of a brain buster i am trying to refactor this method. there are several goals behind doing this, first is so that if anyone reads this code once they can move on because they wouldn't have questions about it.
Second i am hoping there is a faster way of doing this. i mean in my mind its almost like a p vs np thing, but i am sure there are neater ways of accomplishing it. Applying the Solid principles is the goal.
This method receives a string and break it down into individual words. Then it inspects each of the words to find the following suffixes -er, -ers, -ed, -ant, -and and -anned. with each of these suffixes there is a new replacement -er becomes -xor, -ers becomes -xors, -ed becomes -d, -ant, -and and -anned becomes -&(eg. banned becomes b&)
This is what i have so far for the -er and -ers suffixes. its ugly and i bet really slow.
def reconstruct_sentence
s = #sentence.split(/\W+/)
s.each_with_index do |word, i|
if word.end_with?("er")
s[i] = word.chomp("er") + ("xor")
elsif word.end_with?("ers")
s[i] = word.chomp("ers") + ("xors")
else
return
end
s.join(" ")
end
end
I think what i am asking for is far out there and refactoring takes i think a few years of code experience to get used to. but as i go along i can see that this method has more then one purpose breaking solid. so i broke it like this.
def edit_sentence
split_sentence(#sentence) #this would be the sentence that is initialized
sentence.each_with_index do |word, i|
if word.end_with?("er")
sentence[i] = word.chomp("er") + ("xor")
elsif word.end_with?("ers")
sentence[i] = word.chomp("ers") + ("xors")
else
return
end
reconstruct_sentence
end
end
def split_sentence(sentence)
sentence.split(/\W+/)
end
def reconstruct_sentence
sentence.join(" ")
end
the part that i am struggling to re-factor is getting all the suffixes in one method call. i first thought with all the repetition i should use a hash to save all the old suffixes as a key and the new ones as a value but i reckon its going to get complicated like meta programming to the max. any advice? and does anyone know a good book on refactoring patterns?
thanks in advance.
First, your code doesn't work properly, since the return keyword returns from the whole method, instead of continuing.
For a short version of what you try to do, you can use gsub with replacements:
def reconstruct_sentence
#sentence.gsub(/ers?\b/, 'er' => 'xor', 'ers' => 'xors')
end
#sentence = 'this is a tester without any eaters'
reconstruct_sentence
# => "this is a testxor without any eatxors"
More generically you can do:
def reconstruct_sentence
replacements = {'er' => 'xor', 'ers' => 'xors', 'ed' => 'd',
'ant' => '&', 'and' => '&', 'anned' => '&'}
#sentence.gsub(Regexp.union(replacements.keys), replacements)
end
#sentence = 'this is a tester without any planned fighters'
reconstruct_sentence
# => "this is a testxor without any pl& fightxors"

can you define a block inline with ruby?

Is it possible to define a block in an inline statement with ruby? Something like this:
tasks.collect(&:title).to_block{|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}" }
Instead of this:
titles = tasks.collect(&:title)
"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}"
If you said tasks.collect(&:title).slice(0, this.length-1) how can you make 'this' refer to the full array that was passed to slice()?
Basically I'm just looking for a way to pass the object returned from one statement into another one, not necessarily iterating over it.
You're kind of confusing passing a return value to a method/function and calling a method on the returned value. The way to do what you described is this:
lambda {|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}"}.call(tasks.collect(&:title))
If you want to do it the way you were attempting, the closest match is instance_eval, which lets you run a block within the context of an object. So that would be:
tasks.collect(&:title).instance_eval {"#{slice(0, length - 1).join(", ")} and #{last}"}
However, I would not do either of those, as it's longer and less readable than the alternative.
I'm not sure exactly what you're trying to do, but:
If you said tasks.collect(&:title).slice(0, this.length-1) how can you make 'this' refer to the full array that was passed to slice()?
Use a negative number:
tasks.collect(&:title)[0..-2]
Also, in:
"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}"
you've got something weird going on with your quotes, I think.
I don't really understand why you would want to, but you could add a function to the ruby classes that takes a block, and passes itself as a parameter...
class Object
def to_block
yield self
end
end
At this point you would be able to call:
tasks.collect(&:title).to_block{|it| it.slice(0, it.length-1)}
Of course, modifying the Object class should not be taken lightly as there can be serious consequences when combining with other libraries.
Although there are many good answers here, perhaps you're looking for something more like this in terms of an objective:
class Array
def andjoin(separator = ', ', word = ' and ')
case (length)
when 0
''
when 1
last.to_s
when 2
join(word)
else
slice(0, length - 1).join(separator) + word + last.to_s
end
end
end
puts %w[ think feel enjoy ].andjoin # => "think, feel and enjoy"
puts %w[ mitchell webb ].andjoin # => "mitchell and webb"
puts %w[ yes ].andjoin # => "yes"
puts %w[ happy fun monkeypatch ].andjoin(', ', ', and ') # => "happy, fun, and monkeypatch"

RegEx in Ruby: Just one match?

I'm trying to figure out how to check if a string matches a regular expression, but I want to know if the entire string matches just once. Here's my code but it seems absurdly long
def single_match(test_me, regex)
ret_val = false
test = regex.match(test_me)
if (test.length==1 && test[0].length == test_me.length)
ret_val = true
end
return ret_val
end
is there an easier way to do this?
P.S. Here's the method I'm really trying to write, since people always seem to ask why I want the gun these days:
def is_int(test_me)
return single_match(test_me, /[0-9]*/)
end
Edit Thanks everybody. Here's where I'm really using it, but this regex stuff is always interesting to go through. Thanks for the great and educational answers.
You don't need to do this, your method can be replaced by using the regular expression of /^[0-9]*$/. The ^ tells it match start of a line and $ tells it match end of the line. So it will match: start of line, 0 to any in range of 0 to 9, and finally end of line.
def is_int(test_me)
test_me =~ /^[0-9]*$/
end
And you don't need the return statements, Ruby implicitly returns the last statement.
Edit:
It probably would be easier and look better to use the to_i instance method of String class.
def is_int(test_me)
test_me.to_i.to_s == test_me
end
Edit: (did some tests)
Comparing the performance between the two methods shows that .to_i.to_s == way is 5% faster. So it is up to personal preference to which ever looks better and if you want to handle leading zeroes.
To do what you really want should be even simpler
def is_int(test_me)
test_me.to_i.to_s == test_me
end
This?
def single_match(str, regex)
str.match(regex).to_s == str
end
To answer your original question, for the sake of people finding this page in a search, "scan" will return an array of matches, so if you want to find out how many times some regexp matches, e.g. how many runs of digits there are, you can do:
mystring.scan(/\d+/).size

Resources