ruby how to use #capitalize! and keep string numbers [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
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

Related

Ruby, string with a mathematical calculation [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 1 year ago.
Improve this question
In this challenge you must implement the method code that receives a string with a mathematical calculation and returns the value that ? must have for the account result to be correct.
'100 + ? + 3 = 108'
How to find ? value in ruby.
can someone explain how to solve?
Computers are really dumb and need to be told what to do.
Try solving the problem yourself by hand and when it's very clear for you how to solve it, try to implement it.
I'll give you a start
Validate if the input is empty or nil
Split the input into its parts '100 + ? + 3 = 108' => ["100", "+", "?", "+", "3", "=", "108"] (you can put them in an array)
Check if each part is a number, an operator or a ?
If it's a number, transform it from string to number
if It's an operator check which one, +, -, etc. and then act on it taking left and right side of the operator
etc. etc
You'll notice it's not trivial, but eventually each one of those paragraphs can be translated into specific ruby code.
Give it a try and ask again when you get stuck.

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.

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.

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).

refactoring ruby code inject issues [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 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.

Resources