Array.include? myVariable not working as expected - arrays

I am coding a Ruby 1.9 script and I'm running into some issues using the .include? method with an array.
This is my whole code block:
planTypes = ['C','R','S'];
invalidPlan = true;
myPlan = '';
while invalidPlan do
print "Enter the plan type (C-Commercial, R-Residential, S-Student): ";
myPlan = gets().upcase;
if planTypes.include? myPlan
invalidPlan = false;
end
end
For troubleshooting purposes I added print statements:
while invalidPlan do
print "Enter the plan type (C-Commercial, R-Residential, S-Student): ";
myPlan = gets().upcase;
puts myPlan; # What is my input value? S
puts planTypes.include? myPlan # What is the boolean return? False
puts planTypes.include? "S" # What happens when hard coded? True
if planTypes.include? myPlan
puts "My plan is found!"; # Do I make it inside the if clause? Nope
invalidPlan = false;
end
end
Since I was getting the correct result with a hard-coded string, I tried "#{myPlan}" and myPlan.to_s. However I still get a false result.
I'm new to Ruby scripting, so I'm guessing I'm missing something obvious, but after reviewing similar question here and here, as well as checking the Ruby Doc, I'm at a loss as to way it's not acting correctly.

The result of gets includes a newline (\n), which you can see if you print myPlan.inspect:
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C\n"
Add strip to clean out the unwanted whitespace:
myPlan = gets().upcase.strip;
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C"

Related

Execute if else condition parallelly over list of strings

I'm new in python and facing an issue in getting the right output. I have a list of strings as :
list_string=[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
All I want output as:
Output expected: [['The course starts next Sunday'], ["I don't wash the dishes"], 'When does the train usually leave']
What I've done is something:
import re
subtring='!DOC'
output=[]
for i in string:
if subtring in i:
text=re.findall("<p>(.*?)</t>",i, re.DOTALL)
output.append(text)
elif subtring in i:
text=re.findall("<d>(.*?)</span>",i, re.DOTALL)
output.append(text)
else:
output.append(i)
print (output)
[['The course starts next Sunday'], ["class='default'<d>I don't wash the dishes</span>"], 'When does the train usually leave']
Can anyone suggest the right way to do it?
It appears as though the second rule trumps the first so if there is a match on the second rule, use it otherwise try the first rule falling back to returning what you were given.
A solution that is close to what you have now might be:
import re
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output=[]
for line in list_string:
retval = re.findall("<d>(.*?)</span>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
retval = re.findall("<p>(.*?)</t>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
output.append(line)
print (output)
Though if it was me, I would probably use a little function with a comprehension:
import re
def pick_out_text(text):
retval = re.findall("<d>(.*?)</span>", text, re.DOTALL)
if retval: return retval[0]
retval = re.findall("<p>(.*?)</t>", text, re.DOTALL)
if retval: return retval[0]
return text
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output = [pick_out_text(line) for line in list_string]
print(output)

How do I check if an object collides with every object in an array?(Picture boxes)

High school student here and I'm pretty rusty on my code. Okay, I have to have an image scroll along, and if it hits an object(in this case both are picture boxes), it resets.
The problem is when it gets to the If statement below, it won't work saying " 'bounds' is not a member of 'system.array' "
If PtbIcon.Bounds.IntersectsWith(objects.Bounds) Then
The error is the Objects.bounds
If PtbIcon.Bounds.IntersectsWith(objects.Bounds) Then
t = t + 1
PtbIcon.Location = New Point(29, 236)
'resets when you die, sets the score
End If
lblScore.Text = "Your Score Equals" & t
End
Why doesn't this work? Why? Is there a simpler way of checking all of this, such as calling a function which checks the bounds individually?
Use Linq.
Dim t As Integer = 0
PtbIcon.All(Function(pb As PictureBox) As Boolean
' Checking goes here with pb
' Return True if you want to go through all of them
End Function)
lblScore.Text = "Your Score Equals" & t

How do I get matches from a text file and output them in an array?

I'm using a text file with lines of movies. If a user inputs Oz, I want to output all the movies in the file that have the word Oz in it.
This is what I have so far.
puts "Enter the keyword you want to search for: "
keyword = gets
movies_file = File.new("movies.txt", "r")
movies = movies_file.read
movies_list = movies.split(" ")
match_list = []
movies_list.each do |w|
matchObj = w.match(keyword)
if matchObj then
matchlist.push(matchObj.captures[0])
end
end
match_list.each do |title|
puts title
end
Presuming you've got the file organized like this:
Wizard of Oz
Battlefield Earth
Twilight
Ozymandias
Then you can read it in this way:
lines = File.readlines('movies.txt').map(&:chomp)
Then to find matching lines:
matches = lines.grep(phrase)
There's no need for all the each stuff. Also the then on an if is almost never put in there, it's just useless decoration.

Morse Code Decoder in Perl

I am trying to teach myself Perl and I have been struggling... Last night I did a program to calculate the average of a set of numbers that the user provided in order to learn about lists and user input so today I thought I would do a Morse Code decoder to learn about Hashes. I have looked through the book that I bought and it doesn't really explain hashes very well... it actually doesn't explain a lot of things very well. Any help would be appreciated!
Anyways, I am wanting to write a program that decodes the morse code that the user inputs. So the user would enter:
-.-.
.-
-
...
!
.-.
..-
.-..
.
The exclamation point would signify a separate word. This message would return "Cats Rule" to the user. Below is the code I have so far... Remember.. I have been programming in perl for under 24 hours haha.
Code:
use 5.010;
my %morsecode=(
'.-' =>'A', '-...' =>'B', '-.-.' =>'C', '-..' =>'D',
'.' =>'E', '..-.' =>'F', '--.' =>'G', '....' =>'H',
'..' =>'I', '.---' =>'J', '-.-' =>'K', '.-..' =>'L',
'--' =>'M', '-.' =>'N', '---' =>'O', '.--.' =>'P',
'--.-' =>'Q', '.-.' =>'R', '...' =>'S', '-' =>'T',
'..-' =>'U', '...-' =>'V', '.--' =>'W', '-..-' =>'X',
'-.--' =>'Y', '--..' =>'Z', '.----' =>'1', '..---' =>'2',
'...--' =>'3', '....-' =>'4', '.....' =>'5', '-....' =>'6',
'--...' =>'7', '---..' =>'8', '----.' =>'9', '-----' =>'0',
'.-.-.-'=>'.', '--..--'=>',', '---...'=>':', '..--..'=>'?',
'.----.'=>'\'', '-...-' =>'-', '-..-.' =>'/', '.-..-.'=>'\"'
);
my #k = keys %morsecode;
my #v = values %morsecode;
say "Enter a message in morse code separated by a line. Use the exclamation point (!) to separate words. Hit Control+D to signal the end of input.";
my #message = <STDIN>;
chomp #message;
my $decodedMessage = encode(#message);
sub encode {
foreach #_ {
if (#_ == #k) {
return #k;
#This is where I am confused... I am going to have to add the values to an array, but I don't really know how to go about it.
}
else if(#_ == '!') {return ' '}
else
{
return 'Input is not valid';
}
}
}
Your code contains two syntactic errors: foreach requires a list to iterate over; this means parens. Unlike C and other languages, Perl doesn't support else if (...). Instead, use elsif (...).
Then there are a few semantic mistakes: The current value of an iteration is stored in $_. The array #_ contains the arguments of the call to your function.
Perl comparse strings and numbers differently:
Strings Numbers
eq ==
lt <
gt >
le <=
ge >=
ne !=
cmp <=>
Use the correct operators for the task at hand, in this case, the stringy ones.
(Your code #_ == #k does something, namely using arrays in numeric context. This produces the number of elements, which is subsequenty compared. #_ == '!' is just weird.)
What you really want to do is to map the inputted values to a list of characters. Your hash defines this mapping, but we want to apply it. Perl has a map function, it works like
#out_list = map { ACTION } #in_list;
Inside the action block, the current value is available as $_.
We want our action to look up the appropriate value in the hash, or include an error message if there is no mapping for the input string:
my #letters = map { $morsecode{$_} // "<unknown code $_>" } #message;
This assumes ! is registered as a space in the morsecode hash.
We then make a single string of these letters by joining them with the empty string:
my $translated_message = join "", #letters;
And don't forget to print out the result!
The complete code:
#!/usr/bin/perl
use strict; use warnings; use 5.012;
my %morsecode=(
'.-' =>'A', '-...' =>'B', '-.-.' =>'C', '-..' =>'D',
'.' =>'E', '..-.' =>'F', '--.' =>'G', '....' =>'H',
'..' =>'I', '.---' =>'J', '-.-' =>'K', '.-..' =>'L',
'--' =>'M', '-.' =>'N', '---' =>'O', '.--.' =>'P',
'--.-' =>'Q', '.-.' =>'R', '...' =>'S', '-' =>'T',
'..-' =>'U', '...-' =>'V', '.--' =>'W', '-..-' =>'X',
'-.--' =>'Y', '--..' =>'Z', '.----' =>'1', '..---' =>'2',
'...--' =>'3', '....-' =>'4', '.....' =>'5', '-....' =>'6',
'--...' =>'7', '---..' =>'8', '----.' =>'9', '-----' =>'0',
'.-.-.-'=>'.', '--..--'=>',', '---...'=>':', '..--..'=>'?',
'.----.'=>'\'', '-...-' =>'-', '-..-.' =>'/', '.-..-.'=>'"',
'!' =>' ',
);
say "Please type in your morse message:";
my #codes = <>;
chomp #codes;
my $message = join "", map { $morsecode{$_} // "<unknown code $_>" } #codes;
say "You said:";
say $message;
This produces the desired output.
There's a lot of value in learning the how and why, but here's the what:
sub encode {
my $output;
foreach my $symbol (#_) {
my $letter = $morsecode{$symbol};
die "Don't know how to decode $symbol" unless defined $letter;
$output .= $letter
}
return $output;
}
or even as little as sub encode { join '', map $morsecode{$_}, #_ } if you're not too worried about error-checking. #k and #v aren't needed for anything.
Searching for values in hashes is a very intense job, you are better of by just using a reverse hash. You can easily reverse a hash with the reverse function in Perl. Also, while watching your code I have seen that you will be able to enter lower-case input. But while searching in hashes on keys, this is case-sensitive. So you will need to uppercase your input. Also, I do not really like the way to "end" an STDIN. An exit word/sign would be better and cleaner.
My take on your code
my %morsecode=(
'.-' =>'A', '-...' =>'B', '-.-.' =>'C', '-..' =>'D',
'.' =>'E', '..-.' =>'F', '--.' =>'G', '....' =>'H',
'..' =>'I', '.---' =>'J', '-.-' =>'K', '.-..' =>'L',
'--' =>'M', '-.' =>'N', '---' =>'O', '.--.' =>'P',
'--.-' =>'Q', '.-.' =>'R', '...' =>'S', '-' =>'T',
'..-' =>'U', '...-' =>'V', '.--' =>'W', '-..-' =>'X',
'-.--' =>'Y', '--..' =>'Z', '.----' =>'1', '..---' =>'2',
'...--' =>'3', '....-' =>'4', '.....' =>'5', '-....' =>'6',
'--...' =>'7', '---..' =>'8', '----.' =>'9', '-----' =>'0',
'.-.-.-'=>'.', '--..--'=>',', '---...'=>':', '..--..'=>'?',
'.----.'=>'\'', '-...-' =>'-', '-..-.' =>'/', '.-..-.'=>'\"'
);
my %reversemorse = reverse %morsecode;
print "Enter a message\n";
chomp (my $message = <STDIN>);
print &encode($message);
sub encode{
my $origmsg = shift(#_);
my #letters = split('',$origmsg);
my $morse = '';
foreach $l(#letters)
{
$morse .= $reversemorse{uc($l)}." ";
}
return $morse;
}

How do I check for pangrams in a line in ruby?

Some of you may notice I'm already back with the same painful code already. I'm not sure if the other question is still open or not once I accept an answer.
Now the problem is a little simpler. I found some code that checked for pangrams. It use to be def pangram?('sentence') but I needed line to go in there so I tried changing it to def pangram?(line). It doesn't seem to mesh well with my coding style and doesn't work. I tried to use .contain('a' . . 'z') to check for a pangram but someone I know tried that and it didn't work. Also google isn't much help either.
Any ideas for how I could check for pangrams in an if stmt?
# To change this template, choose Tools | Templates
# and open the template in the editor
# This program reads a file line by line,
#separating lines by writing into certain text files.
#PPQ - Pangrams, Palindromes, and Quotes
class PPQ
def pangram?(line)
unused_letters = ('a'..'z').to_a - line.downcase.chars.to_a
unused_letters.empty?
end
def categorize
file_pangram = File.new('pangram.txt', 'w')
file_palindrome = File.new('palindrome.txt', 'w')
file_quotes = File.new('quotes.txt','w')
File.open('ruby1.txt','r') do |file|
while line = file.gets
if(line.reverse == line)
file_palindrome.write line
elsif(pangram?(line)== true)
file_pangram.write line
else
file_quotes.write line
end
end
end
file.close
file_pangram.close
file_palindrome.close
file_quotes.close
end
end
my_ruby_assignment = PPQ.new
my_ruby_assignment.categorize
I'm partial to simpler syntax, something like
def pangram?(line)
('a'..'z').all? { |word| line.downcase.include? (word) }
end
if pangram?(line) then file_pangram.write line end
def pangram?(string)
str = string.chars.map(&:downcase)
letters =('a'..'z').to_a
result = true
letters.each do |l|
if !(str.include? l.downcase)
result = false
break
end
end
result
end

Resources