refactoring ruby code inject issues [closed] - ruby

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 can someone explain to me why my inject isn't working here?
Am I using inject correctly here? For some reason my code gets caught up in an endless loop once this scenario comes into play (the 5th move usually in my game)
def cpu_block_player
winning_combinations = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
executed = 0
winning_combinations.each do |combination|
result_of_combination = ""
result_of_combination = combination.inject("") {|result, element| result + #board[element]}
if result_of_combination == "XXe" || result_of_combination == "eXX" || result_of_combination == "XeX"
executed += 1
puts executed
player_move(#current_turn, result_of_combination.index("e"))
end
break if executed >= 1
end

First of all, these kinds of questions are better suited for the Code Review Stack Exchange site.
However, here are my thoughts:
My first thought when looking at your code is that you're just having one large class. In order to see some real advantages with Object-Oriented Programming, I'd recommend extracting some of the code into separate classes. I can definitely see a Board class inside the Game class, just waiting to be extracted.
Some ideas for methods to add to a Board class:
to_s -- This would be what's in your print_board method at the moment, without the print.
finished? -- Check whether the game is "finished" (ie., someone has won). A winner method would also make sense.
taken? -- Whether someone has taken a position before.
A lot of the code in your Game class would benefit from naming. For instance, take this piece of code:
#current_turn == #player_x ? #current_turn = #player_o : #current_turn = #player_x
It's not super hard to figure out what this piece of code does, but exactly how you swap who is the current player is probably not important to know while reading the player_move method. All you want to know is that "at this point, we switch players".
Extracting methods and objects doesn't make you write less code, but in my opinion it makes for clearer code. If you can give every piece of line a name (ie., extract it to a method), then it is probably a lot easier to figure out what is going on.

Related

self referencing an object in its assignment [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 was wondering if there was a way to reference an object when assigning it to a variable. Here is an example of where this question would apply:
Let's say I wanted to assign the substring of a regex to a variable, call it i.
To assign, I could write
i = /some_regex/.to_s
and then
i = i[3...i.length]
I could also write it all in one line, like
i = /some_regex/.to_s[3.../some_regex/.to_s.length]
However, both of these examples seem somewhat redundant and the second approach could become unwieldy with big regex's or multiple method calls. Is there a way to reference the object being changed without having to rewrite everything?
Edit: Sorry for previous ambiguity.
Ruby evaluates the right side of the equals sign before setting the left side equal to it, so if i already exists you can do what you're talking about. A simple example:
i = 10
i = i + 1 # now i = 11
However, you can't use i to define itself. You could use the following two lines:
i = expression.match(/\d+[\+|-|\*|\/]/)
i = i[0..i.length - 1] # Note: this is the same as i = i[0...i.length]

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.

ruby how to use #capitalize! and keep string numbers [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
so I'm doing prep work for a ruby dev bootcamp and need to create a program that will capitalize titles. My current code uses #capitalize! but when a number is included in the string it is omitted.
words = title.split(' ')
words.map! do |word|
if %w(a aboard about above absent across after against along alongside amid amidst among amongst an and around as aslant astride at
athwart atop barring before behind below beneath beside besides between beyond but by despite down during except for from in inside
into like mid minus near next nor notwithstanding of off on onto opposite or out outside over past per plus regarding round save
since so than the through throughout till times to toward towards under underneath unlike until up upon via vs. when with within
without worth yet ).include?(word) && word != words[0]
word
else
word.capitalize!
end
so when what I wish I knew when I was 20 is input I get What I Wish I Knew When I Was
any suggestions?
Use capitalize instead of capitalize!.
By the way, if your intention of word != words[0] is to leave any word in the list uncapitalized if it is not the first word, then you are wrong. It does not work like that. The reason is left to you as a homework.
just change word.capitalize! to word.capitalize! || word
"20".capitalize! #=> nil
"20".capitalize! || "20" #=> 20

Accidental NilClass in my instance variables [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 9 years ago.
Improve this question
I am making a dating simulator. One of the first things I need is to keep track of the way characters feel about each other. In this sim, anyone can date anyone else, and there are two variables for relationship (one for love and one for friendship).
So I thought the easiest way to do this would be for each character to have a separate class that kept track of how they felt about everyone else. Below is one such sample class. I also thought that the easiest way to keep track of where points should be added was by giving each character a hash that pointed to their own variable, and then using a swap function to trade targets with the person they are speaking to.
However, I am getting an error message.
class HRelatStatus
def initialize
{#target=> #hrelat}
#krelat =[10, 10]
#arelat =[9, 4]
#srelat =[13, 11]
#jrelat =[12, 1]
#brelat =[5, 5]
#hrelat=[0, 0]
end
def dataaccess
attr_accessor :target, :krelat, :arelat, :srelat, :jrelat, :brelat, :hrelat
end
def makehappy
#target[0] = #target[0]+1
end
end
hfeels=HRelatStatus.new
puts #krelat.class
puts #krelat[1]
hfeels.makehappy
puts #target[0]
When I try to run this, #krelat comes back as a Nil class. And when I try to run the makehappy method (or any method, really) I get the error message undefined method '[]' for nil class.
How do I stop my instance variables from being nil classes? How can I sucessfully make methods that will add to one variable in the array for a specific character? And does anyone have a better idea for how I can specify who to target?
You are saying:
hfeels=HRelatStatus.new
puts #krelat.class
But there is no such thing as #krelat in this context. What you are after is the krelat instance variable inside your instance, i.e. hfeels.krelat.
(Of course, that won't work either because you've hidden your accessor generators inside an instance method.)
The first thing you actually need to do is learn how Ruby (or really, variable scope in any language) works.
#krelat outside of the class is totally unrelated to #krelat inside the class.
The makehappy method won't work because { #target => #hrelat } doesn't do anything in Ruby (well, it creates a hash with a nil key pointing to a nil value and then discards that hash. Ie. effectively nothing.
This code is a total mess, learn Ruby first. Buy "Programming Ruby" and read it.

exception in if statement [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 9 years ago.
Improve this question
I wrote a searcher function in ruby for a class that iterates on a list of people (named #personList).
It faces an exception.
My Code‌ :
def search (nCode)
for x in #personList
if x.nCode == nCode
x.to_s
end
end
I wrote the same code using each, it also faced the same exception.
What's wrong with my code ?
(I'm new to Ruby! and I couldn't solve that)
This if is delimited by a pair of newlines:
x.to_s if x.nCode == nCode
This if needs an explicit end:
if x.nCode == nCode
x.to_s
end
You have opened three blocks (def, for..in, if) in your first sample, but only closed two. Your indentation indicates the if is the one you didn't close. Thus, you have a syntax error. Otherwise, both samples are identical in functionality.
Ruby if requires an end to make it complete. If you use end for your exception code, it will work.
if x.nCode == nCode
x.to_s
end
For second case, that worked or you, it is actually completes the condition and the execution in one line. That's why it didn't require any end, and it worked for you.
You'll find more detail about if from here.

Resources