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 3 years ago.
Improve this question
A
B B
C C C
D D D D
E E E E E
I don't know, how to print alpahbets
You can do the following to work it out:
('A'..'F').each.with_index(1) { |letter,index| puts "#{letter} "*index }
Alternatives include making the ranges variable:
lower_limit = 'A' # could be read in rather than wired
upper_limit = 'F' # ditto
(lower_limit..upper_limit).each.with_index(1) { |letter,index| puts "#{letter} "*index }
or using an array with join to get the spaces without introducing a trailing blank:
(lower_limit..upper_limit).each.with_index(1) { |letter,index| puts Array.new(index) { letter }.join(' ') }
You can do something like -
(1..5).each do |index|
(1..index).each do
print (64+index).chr
end
puts "\n"
end
What it does -
(1..5) - Run a loop with index starting from 1 up until 5.
(1..index) - run another loop so for each of the above loop, it runs from 1 up till index, which will be controlled from the (1..5).each loop.
(65).chr -> A, (66).chr -> B and so on..
puts "\n" to add a new line
That will give you the output -
A
BB
CCC
DDDD
EEEEE
If you want to add anything additional to whatever you are printing you can do something like -
print "#{(64+index).chr} - random text"
#{} construct will allow you to write ruby interpret-able code within a string block`
Note: #{} only works when you use double quotes :)
Its not for RUBY nor for any other language, its just a flow :
Print alphabets like :
for (ch = 'a'; ch <= 'z'; ch++)
{
System.out.println(ch);
}
Now initialise counter i = 0
Increment i++ in every loop.
Print the current outer loops current char, i times
Related
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 6 years ago.
Improve this question
I'm trying to create a loop that add 1 to the idx every time theres a vowel in the string, but my code returns nothing.
def count_vowels(string)
vowlcounter = 0
idx = 0
words = string.split('')
while idx < string.length
if words[idx] == 'a'||'e'||'i'||'o'||'u'
vowlcounter += 1
idx += 1
end
end
return vowlcounter
end
You can use Regular expressions for shorter comparison if the string or char is a vowel. The other way like you wanted to would be way too long:
if words[idx] == 'a' || words[idx] == 'e'
And so on ...
Also if you would just increment idx everytime you have actually a vowel, you would get stuck in an infinite loop if the char isnt a vowel, idx would not increase, thus always checking for the same value in the while loop.
This code works by using Regular expression:
def count_vowels(string)
vowlcounter = 0
idx = 0
while idx < string.length
if string[idx][/[aeiou]/]
vowlcounter += 1;
end
idx += 1;
end
return vowlcounter
end
Scan and Count Vowels
This strikes me as an X/Y problem. Rather than debugging your code, it may be better to simply use built-in String methods to count your vowels, rather than doing your own iteration through the string. Other people can address the Y in your X/Y problem, but I'd rather help you solve for X directly.
Using String#scan
Use String#scan and Array#count to do this quickly and easily. While this doesn't account for y when used as a vowel, it should otherwise do what you want.
def vowel_count str
str.scan(/[aeiou]/).count
end
vowel_count 'foo'
#=> 2
vowel_count 'foo bar baz'
#=> 4
Using String#count
I like using #scan best, because it returns an array you can use elsewhere if you like and helps with debugging. However, if you don't care about which vowels are found, you can use the String#count method directly. For example:
def vowel_count str
str.count 'aeiou'
end
vowel_count 'foo'
#=> 2
vowel_count 'foo bar baz'
#=> 4
The results are the same, but you loose the ability to introspect the values returned inside your method. YMMV.
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 6 years ago.
Improve this question
How do i print a name Ex. John1 and then print after John2, john3, john4, john5 and so one in an infinite number
I started using ruby today and I'm having some trouble figuring this out. I've searched some but can't find anything so how would I do this?
It's to mass produce accounts to the staff of a certain company and I found ruby to be the smartest to write it in and I will never use it again after this
Keep it simple.
puts (1..5).map { |n| "john#{n}" }
john1
john2
john3
john4
john5
The class Range includes the module Enumerable (as does the classes Array, Hash and others). By doing so, instances of Range (such as 1..5) gain the use of all of Enumerable's instance methods. One of Enumerable's instance methods is used here: Enumerable#map.
For printing a simple series like this:
n = 1
loop do
print 'john%d, ' % n
n += 1
end
That will never terminate, which makes it kind of silly. Maybe what you want is a bounded range:
list = (1..10).map do |n|
'john%d' % n
end.join(', ')
puts list
You can adjust the start and end values as necessary.
Perhaps use an enumerator here:
enum = Enumerator.new do |y|
i = 1
loop do
y << "John#{i}"
i += 1
end
end
enum.next #=> "John1"
enum.next #=> "John2"
enum.next #=> "John3"
Then use any one of the methods available to instances of Enumerator. Here we've used Enumerator#next to get the next "John" string.
One simple way is using a for loop. First declare an empty string variable that will hold our contents.
One important thing to consider is the index of the loop. If it's the last item, we do not want to add a separator like ", "
This is where the conditional comes into play. If the index is less than the last, we will add a comma and space, otherwise just the name.
Interpolation is done by wrapping a variable inside #{ and }
str = ""
for i in 1..5
str += i < 5 ? "john#{i}, " : "john#{i}"
end
Returns
"john1, john2, john3, john4, john5"
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
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Which is better?
string.each_char do |letter|
unless letter == " "
if letters.has_key?(letter)
letters[letter] = letters[letter].next
else
letters[letter] = 1
end
end
end
or
string.each_char do |letter|
if letter == " "
elsif letters.has_key?(letter)
letters[letter] = letters[letter].next
else
letters[letter] = 1
end
end
It seems awkward to leave an if statement without the body, but it also seems preferable to going a step deeper with unless.
There's a better way to write this code. I didn't know about default Hash values, and that would clean this code up a lot, but I still wanted to know which is preferable: an if statement without body, or unless, or something else.
This is probably the nicest:
letters = Hash.new(0)
string = "aaabbc"
string.each_char do |letter|
if letter != " "
letters[letter] += 1
end
end
# => {"a"=>3, "b"=>2, "c"=>1}
For deciding between your two examples, I would avoid adding extra-depth (more indentation). The second one is also easier to read because it's simple to follow a string of if/else statements. It's almost always preferable to have more readable code than fancy code.
You can set the default value for a hash when constructing:
letters = Hash.new(0)
...
letters[letter] = letters[letter].next
An interesting approach using this is to use some of the map / reduce methods offered by Ruby:
letters = string.chars
.reject{ |letter| letter == " " }
.each_with_object(Hash.new(0)) { |letter, memo|
memo[letter] = memo[letter].next
}
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 dont want to use if statement.
count = 0
10.times do |i|
all = (i..20).collect{ |ii| ii < rand(30) || break }
count+=1 if all # i dont want to use `if` statement
end
p count
How can I do that?
I got something in the similar matter:
count = 0
10.times do |i|
(i..20).collect{ |ii| ii < rand(30) || break } || next
count += 1
end
So it is just boolean algebra. if condition is taken place, when all, i.e. result of collect method, isn't nil, so we need to next keyword worked, when result of collect is nil. Therefore we just set or operator between collect and next, in order to next is occuring when result of collect is nil.
count = (0..9).count { |i| (i..20).all?{ |j| j < rand(30) } }