Factoring Polynomial exercise in ruby, unexpected syntax? [closed] - ruby

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I got these errors --
(eval):30: (eval):30: compile error (SyntaxError)
(eval):8: syntax error, unexpected kDO
-- when I ran this ruby code in console --
class Factor
puts "This program will factor a polynomial in the form of \"Ax^2 + Bx + C.\""
aPos = PosOrNeg?("A")
# test
puts aPos
def PosOrNeg?(string = "blank") do
puts "Tell us if \"#{string}\" is positive or negative. Type \"pos\" or \"neg\"."
posOrNegStr = gets.chomp
case posOrNegStr
when "pos"
pos = true
when aPosOrNegStr = false
pos = false
else
while posOrNegStr != "pos" && posOrNegStr != "neg" do
puts "Invalid input. Please type \"pos\" or \"neg\"."
posOrNegStr = gets.chomp
case posOrNegStr
when "pos"
pos = true
when aPosOrNegStr = false
pos = false
else
end
end
end
end
end
Thoughts?

Look at lines:
# test
puts aPos
def PosOrNeg?(string = "blank") do # <- here!!
Here's an ideal syntax for defining a method in Ruby:
def method_name
# method body
end
So, change def PosOrNeg?(string = "blank") do to def PosOrNeg?(string = "blank").
Note: In Ruby the coding style for defining a method or an object is snake_cased, which is pretty famous among the Ruby community. It'd be much better if you name your method to be something like: pos_or_neg?(string = 'blank').

Related

ruby not equal operator doesn't work but equal does [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm very puzzled with this simple method I have where I'm just trying to puts a character of an array if, when compared with the character of another array, it is different.
This works with the == operator but not with the !=
Maybe it has to do with the each loops but I can't see what the error is. Any ideas?
Thanks
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = []
nw_s.each do |char|
vowels.each do |vowel|
if char != vowel
print char
end
end
end
end
remove_vowels("apple")
Nested each is no ruby way of doing this kind of task. You can write this
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = nw_s.map {|k| k unless vowels.include?(k) }.compact
end
remove_vowels("apple")
One line of code instead seven

How to get hash in a given array list in Ruby? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
My Ruby question is in a given array of non-empty strings, create and return a hash as follows: for each string add its first character as a key with its last character as a value in defn method
def pairs1(arry)
arry = [ "code", "bug"]
final_hash = {}
pairs1.each do |var|
final_hash[] = puts var[0] puts var[-1]
final_hash[var[0]] = var[-1]
end
puts final_hash
The error I got is :
syntax error, unexpected tIDENTIFIER, expecting keyword_end
...final_hash[] = puts var[0] puts var[-1]
... ^~
Looking at your code:
def pairs1(arry)
arry = [ "code", "bug"]
final_hash = {}
pairs1.each do |var|
final_hash[] = puts var[0] puts var[-1]
final_hash[var[0]] = var[-1]
end
puts final_hash
A few things are a bit off. You should remove the array initialization (arry = [...]) because you're passing in a array through the parameters of the method already. If you keep it like this, passing a parameter won't have any effect on the method. Also this line final_hash[] = puts var[0] puts var[-1] doesn't do anything (aside from raising an error), so you can remove it too. You also want to call the #each methon on the array, calling it on the method itself doesn't make much sense here. If you also add an end to the end of the method you get a working version of your method:
def pairs1(arry)
final_hash = {}
arry.each do |var|
final_hash[var[0]] = var[-1]
end
puts final_hash
end
Keep in mind, this method currently doesn't return the value of final_hash, it just prints the value to the console and returns nil. If you want to change that just remove the puts from the last line.
You can also do something like this:
arry = [ "code", "bug"]
def pairs1(arry)
arry.each_with_object({}) { |element,hash| hash[element[0]] = element[-1] }
end
pairs1(arry)
# => {"c"=>"e", "b"=>"g"}
You forgot to add end to the close defining of the method.
You can use inject method too. And for readability I prefer chars.first and chars.last
arry = ['code', 'bug']
final_hash = arry.inject({}) do |memo, val|
memo[val.chars.first] = val[val.chars.last]
memo
end
p final_hash
{"c"=>"e", "b"=>"g"}

How to solve ruby string [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
I'm new to ruby, and I'm trying to make a simple calculator in which a user types in a simple problem (such as addition or subtraction) and the answer is returned. The problem is when the user types in a question, the question itself is being returned instead of the answer to that question.
puts "How many Questions?"
questions = gets.chomp.to_i
questions.times do |problem|
puts "question: "
problem = gets.chomp
puts "answer: #{problem}"
end
Inside your loop, instead of:
problem = gets.chomp
puts "answer: #{problem}"
Try this:
problem = gets.chomp
solved_problem = eval(problem)
puts "answer : #{solved_problem}"
eval will take care of interpreting your string as a Ruby instruction. But it's very messy, because anyone could write any Ruby program in your input and eval will make it run, so it's not safe at all.
If you only want to take care of simple operations, you can use a regex first to check if the input string looks like what you want:
problem_is_ok = (problem =~ /^\d+ *[+-] *\d+$/)
This will be true if the string starts with a number, followed by 0 to many spaces, followed by either a + or - sign, followed by 0 or more spaces, followed by another number and nothing else. Then you raise an error if this is not true.
Your loop now look like this:
questions.times do |problem|
puts "question: "
problem = gets.chomp
problem_is_ok = (problem =~ /^\d+ *[+-] *\d+$/)
if problem_is_ok
puts "answer: #{eval(problem)}"
else
#I raise an error, but you might aswell just print it instead for your simple program
raise ArgumentError("Can't compute this")
end
end
Add and subtract can be simple ruby definitions
We pass in 5 and 1
The lower portion of the code is the clear user interface implementation
when we loop we do it 3 times
It outputs 3 options for the user to select from
We read in with chomp, standard in, the keyboard, chooses 1, 2, or 3
If elsif statements conditionally select for each case
Using string interpolation we render the variables a and b into a new string,
and run their respective methods (add or subtract)
Converting that methods integer output to a string, and concatenate it.
Outputting that to the users screen
The 3rd option does no calculation,
instead it prints to users screen a simple string
our else condition catches the case when people don't enter one of the choices of 1, 2 or 3
It tells you to correct your choice to the options provided
Hope this helps
#!/usr/bin/env ruby
questions = 3
a, b = 5, 1
def add(a,b)
a + b
end
def subtract(a,b)
a - b
end
questions.times do |questions|
puts "Please choose:
1. add
2. subtract
3. exit"
questions = gets.chomp
if questions == '1'
puts "#{a} + #{b} = " + add(a,b).to_s
elsif questions == '2'
puts "#{a} - #{b} = " + subtract(a,b).to_s
elsif questions == '3'
puts 'exiting, goodbye.'
exit
else
p 'please choose again'
end
end

Learn Ruby the Hard Way #41 [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
Hi I`m learning from LRtHW and I got stuck....
I have program like this:
require 'open-uri'
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class ### < ###\nend" => "Make a class named ### that is-a ###.",
"class ###\n\tdef initialize(###)\n\tend\nend" => "class ### has-a initialize that takes ### parameters.",
"class ###\n\tdef ***(###)\n\tend\nend" =>"class ### has-a function named *** that takes ### parameters.",
"*** = ###.new()" => "Set *** to an instance of class ###.",
"***.***(###)" => "From *** get the *** function, and call it with parameters ###.",
"***.*** = '***'" => "From *** get the *** attribute and set it to '***'."
}
PHRASE_FIRST = ARGV[0] == "english"
open(WORD_URL) do |f|
f.each_line {|word| WORDS.push(word.chomp)}
end
def craft_names(rand_words, snippet, pattern, caps=false)
names = snippet.scan(pattern).map do
word = rand_words.pop()
caps ? word.capitalize : word
end
return names * 2
end
def craft_params(rand_words,snippet,pattern)
names = (0...snippet.scan(pattern).length).map do
param_count = rand(3) + 1
params = (0...param_count).map {|x| rand_words.pop()}
params.join(', ')
end
return names * 2
end
def convert(snippet, phrase)
rand_words = WORDS.sort_by {rand}
class_names = craft_names(rand_words, snippet, /###/, caps=true)
other_names = craft_names(rand_words, snippet,/\*\*\*/)
param_names = craft_params(rand_words, snippet, /###/)
results = []
for sentence in [snippet, phrase]
#fake class name, also copies sentence
result = sentence.gsub(/###/) {|x| class_names.pop}
#fake other names
result.gsub!(/\*\*\*/) {|x| other_names.pop}
#fake parameter list
result.gsub!(/###/) {|x| param_names.pop}
results.push(result)
end
return results
end
# keep going until they hit CTRL-D
loop do
snippets = PHRASES.keys().sort_by { rand }
for snippet in snippets
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST
question, answer = answer, question
end
print question, "\n\n> "
odp = gets.chomp
if odp == "exit"
exit(0)
end
#exit(0) unless STDIN.gets
puts "\nANSWER: %s\n\n" % answer
end
end
I understand most of this code, but I have a problem with:
for sentence in [snippet, phrase]
I know that it is a "for" loop and it creates a "sentence" variable, but how does the loop know that it need to look in a key and value of hash "PHRASES"
And my second "wall" is:
question, answer = convert(snippet, phrase)
It looks like it creates and assigns "question" and "answer variables to the "convert" method with "snippet" and "phrase" parameters... again how does it assigns "question" to a key and answer to a value.
I know that this is probably very simple but as for now it blocks my mind :(
For your first question about the for-loop:
Look at where the for-loop is defined. It's inside the convert() method, right? And the convert() method is passed two arguments: one snippet and one phrase. So the loop isn't "looking" for values in the PHRASES hash, you are the one supplying it. You're using the method's arguments.
For your second question about assignment:
In Ruby we can do something called "destructuring assignment". What this means is that we can assign an array to multiple variables, and each variable will hold one value in the array. That's what's happening in your program. The convert() method returns a two-item array, and you're giving a name (question and answer) to each item in the array.
Here's another example of a destructuring assignment:
a, b, c = [1, 2, 3]
a # => returns 1
b # => returns 2
c # returns 3
Try this out in IRB and see if you get the hang of it. Let me know if I can help clarify anything, or if I misunderstood your question. You should never feel bad about asking "simple" questions!

Refactoring ugly ruby code [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
The code below gets some text, find commas, and returns an array of a split up version without the commas.
class A
def separate_comma_values(text)
txt_len = text.length
if txt_len == 0
return [""]
end
final = []
sub_arry = ""
for i in (0...txt_len)
ch = text[i]
if ch == ","
final << sub_arry
final << ""
sub = ""
else
sub_arry += ch
end
end
return final
end
end
This is a sample input and output:
s = A.new
print s.separate_comma_values("dh,,,dhhd,jhb")
# => ["dh", "", "dh", "", "dh", "", "dhdhhd", ""]
Although it does what I want it to do, I feel that there is something just not right about it. It's just dirty.
I am aware that I can use a built in method provided by ruby to achieve the split.
Edit: I guess this was edit out of my original post. The motivation behind this was to apply the knowledge I found after reading a ruby book.
There's a method in Ruby that does what you want.
http://ruby-doc.org/core-2.0/String.html#method-i-split
2.0.0p0 :001 > "dh,,,dhhd,jhb".split(',')
=> ["dh", "", "", "dhhd", "jhb"]
So, your code might end up being as simple as
def separate_comma_values(text)
text.split(',')
end
Update: Sorry, I missed the part where you mention you already know about split. Oops.
The only proper way to refactor your code is, obviously, to use String#split.
Although, just for fun:
def separate_comma_values(text)
text.each_char.reduce(['']) do |splitted, char|
if char == ','
splitted << ''
else
splitted.last << char
end
next splitted
end
end
Just as a small trick for looking nicer (in my opinion), you should be able to skip the word 'return' at the end of the method, and your 'seperate_comma_values(text)' could be just 'seperate_comma_values text' without the parens (in your text editor, syntax color highlighting makes this not a problem of clarity at all)
This is a little cleaner, although as #depa points out, if you're trying to split based on commas, there's an easier way, and your (and thus this) code doesn't work right.
class A
def separate_comma_values(text)
return [""] if text.empty?
final = []
sub_arry = ""
text.each_char do |ch|
if ch == ","
final << sub_arry
final << ""
else
sub_arry += ch
end
end
return final
end
end
s = A.new
print s.separate_comma_values("dh,,,dhhd,jhb")
puts
This outputs
["dh", "", "dh", "", "dh", "", "dhdhhd", ""]
just as your does.
Here's how I would implement your algorithm:
class A
def separate_comma_values(text)
return [""] if text.empty?
array = []
value = ""
text.each_char do |c|
if c == ","
array << value
value = ""
else
value += c
end
end
array << value if !value.empty?
array
end
end
s = A.new
print s.separate_comma_values("dh,,,dhhd,jhb")
puts
This outputs
["dh", "", "", "dhhd", "jhb"]

Resources