Code:
arr = [[1,2,3],[4,5,6],[7,8,9]]
a=0
b=0
while b <= 2
a=0
while a <= 2
print arr[a][b]
a+=1
end
b+=1
puts " "
end
Output:
147
258
369
Is there a quicker way of achieving the same result?
I am just a beginner, so don't make it too had.
You can use puts for each line.
arr.transpose.each{|l| puts "#{l.join} "}
would give the same result as you did, but perhaps you wanted
arr.transpose.each{|l| puts l.join}
This should do:
arr = [[1,2,3],[4,5,6],[7,8,9]]
puts arr.transpose.map(&:join).join(' ')
# => 147 258 369
Yes, using #join method:
print arr.transpose.map { |a| a.join('') }.join(' ')
or if each value should be in different line, then you can write
puts arr.transpose.map { |a| a.join('') }
Related
Based on the link
I tried to delete "" in the array on ruby
However still not get what I want, if anyone knows, please advice me
a = gets
lines = []
aaa = []
b = []
bb =[]
while line = gets do
lines << line.chomp.split(' ')
end
for k in 0..(lines.size - 1) do
b << lines[k][1].to_i + 1
end
for i in 0..(lines.size - 1)do
bb << lines[i][0] + ' ' + b[i].to_s
end
for l in 0..(lines.size - 1)do
p bb[l]
end
Input
3
Tanaka 18
Sato 50
Suzuki 120
Output
[["Tanaka", "18"], ["Sato", "50"], ["Suzuki", "120"]]
"Tanaka 19"
"Tanaka 19"
"Sato 51"
"Suzuki 121"
As pointed out in the comments, you can get rid of the quotation marks by replacing p (Ruby's inspect/print) with puts.
While we're at it, you can make this much more "Ruby-ish" by using .readlines to scoop up all the input into an array, and by replacing the multiple counting loops with .map or .each iterators. The following is more concise, and allows you to lose the first input line which you're just throwing away anyway.
lines = STDIN.readlines(chomp: true).map do |line|
l = line.split(' ')
[l[0], l[1].to_i + 1].join(' ')
# or
# "#{l[0]} #{l[1].to_i + 1}"
end
lines.each { |line| puts line }
With Ruby 3, you can use rightward-assignment for the first part if you find it more readable:
STDIN.readlines(chomp: true).map do |line|
l = line.split(' ')
"#{l[0]} #{l[1].to_i + 1}"
end => lines
I'm struggling to figure out how to loop numbers in a single line on ruby.
x = 0
while x <= 9
puts x
x +=1
end
This would give you
0
1
2
3
4
5
6
7
8
9
Each on different lines.
But what I want is to get this on a single line so like
01234567891011121314151617181920
Also not limited to just 0-9 more like 0 to infinity on a single line.
The purpose is to make an triangle of any size that follows this pattern.
1
12
123
1234
12345
123456
Each of these would be on a different line. The formatting here won't let me put in on different lines.
Would really like to solve this. It is hurting my head.
try this:
(1..9).each { |n| print n }
puts
You said you want "to make a triangle of any size that follows this pattern", so you should not make assumptions about how that should be done. Here are two ways to do that.
#1
def print_triangle(n)
(1..n).each.with_object('') { |i,s| puts s << i.to_s }
end
print_triangle(9)
1
12
123
1234
12345
123456
1234567
12345678
123456789
#2
def print_triangle(n)
s = (1..n).to_a.join
(1..n).each { |i| puts s[0,i] }
end
print_triangle(9)
1
12
123
1234
12345
123456
1234567
12345678
123456789
how about this solution:
last_num = 9
str = (1..last_num).to_a.join # create string 123456789
0.upto(last_num-1){ |i| puts str[0..i] } # print line by line
puts (1..9).map(&:to_s).join
Regarding your final aim there are lots of (probably easier) ways, but here's one:
def print_nums k
k.times { |n| puts (1..(n+1)).map { |i| i*10**(n+1-i) }.inject(:+) }
end
print_nums 9
#1
#12
#123
#1234
#12345
#123456
#1234567
#12345678
#123456789
This approach generates the actual numbers using units, tens, hundreds etc in relation to the line number i.
Thought Process
Looking at a basic example of four lines:
1
12
123
1234
is the same as:
1*10**0 #=> 1
1*10**1 + 2*10**0 #=> 12
1*10**2 + 2*10**1 + 3*10**0 #=> 123
1*10**3 + 2*10**2 + 3*10**1 + 4*10**0 #=> 1234
which in Ruby can be generated with:
(1..1).map { |i| i*10**(1-i) }.inject(:+) #=> 1
(1..2).map { |i| i*10**(2-i) }.inject(:+) #=> 12
(1..3).map { |i| i*10**(3-i) }.inject(:+) #=> 123
(1..4).map { |i| i*10**(4-i) }.inject(:+) #=> 1234
looking for a pattern we can generalise and put in a method:
def print_nums k
k.times { |n| puts (1..(n+1)).map { |i| i*10**(n+1-i) }.inject(:+) }
end
You could (and should) of course ignore all of the above and just extend the excellent answer by #seph
3.times { |i| (1..(i+1)).each { |n| print n }; puts }
#1
#12
#123
The simplest way if you want to start from 1
9.times {|n| puts n+1}
try if you want to start from 0
10.times {|n| puts n}
if you want pyramid format this is one way to do
9.times{|c| puts (1..c+1).to_a.join}
this is the ouput
2.3.0 :025 > 9.times{|c| puts (1..c+1).to_a.join}
1
12
123
1234
12345
123456
1234567
12345678
123456789
I want to create a table:
Iterations Value
1 123
2 124
..
100 124212
101 1242142
If I'm able to do so, do you know which website for reference is good for Ruby?
Already asked here:
Is there a Ruby equivalent to the C++ std::setw(int) function?
puts "%10s" % ["foo"] # => " foo"
puts "%-10s" % ["bar"] # => "foo "
You can use rjust or ljust.
"123".rjust(10, '0')
#=> "0000000123"
"123".ljust(10, '0')
#=> "1230000000"
I have a random amount of days that I'm iterating through like this:
#days.each_slice(7) {|week|}
and would like to know when I'm on the last set of days (i.e. the last week). What would be an efficient way to do this?
The simplest way I can think of is by defining this algorithm to detect the last slice of an array:
def last_slice( array, i )
last_slice = (array.count % i == 0) ? i : array.count % i
array.last( last_slice )
end
and then compare it like:
if ( week == last_slice( #days, 7 ) )
#days.each_slice(7).with_index do |week,i|
if i == (#days.size-1)/7
# last one
end
...
end
Alternatively, if your code in the block is highly divergent for the last week:
weeks = #days.each_slice(7).to_a
weeks[0...-1].each {|week| ... }
weeks[-1].tap {|last_week| ... }
It's a hint,hope will help you:
ar = [1,2,3,1,2,3,"a","b","c"]
e = ar.each_slice(3)
e.size.times do |i|
begin
i = e.next
e.peek
rescue StopIteration
p "reached last iteration : #{i}"
end
end
#=> "reached last iteration : [\"a\", \"b\", \"c\"]"
or You could do as below:
e = ar.each_slice(3)
e.with_index{|i,ind| p i if ind == e.size - 1 }
#=> ["a", "b", "c"]
or You could do as below too:
ar = [1,2,3,1,5,3,"a","b","c"]
e = ar.each_slice(3)
e.size.times{|i| i = e.next;p i if !(e.peek rescue nil) }
#=> ["a", "b", "c"]
#days.each_slice(7) { |week| if (week.last == #days.last) then <your code here> end }
I don't have knowledge of ruby but did you try this in your loop ?
#days.each_slice(7) {|week|
if week.last # do stuff...
}
Here is the Ruby Doc for the each_slice method :
http://ruby-doc.org/core-2.0/Enumerable.html#method-i-each_slice
Sample input:
"I was 09809 home -- Yes! yes! You was"
and output:
{ 'yes' => 2, 'was' => 2, 'i' => 1, 'home' => 1, 'you' => 1 }
My code that does not work:
def get_words_f(myStr)
myStr=myStr.downcase.scan(/\w/).to_s;
h = Hash.new(0)
myStr.split.each do |w|
h[w] += 1
end
return h.to_a;
end
print get_words_f('I was 09809 home -- Yes! yes! You was');
This works but I am kinda new to Ruby too. There might be a better solution.
def count_words(string)
words = string.split(' ')
frequency = Hash.new(0)
words.each { |word| frequency[word.downcase] += 1 }
return frequency
end
Instead of .split(' '), you could also do .scan(/\w+/); however, .scan(/\w+/) would separate aren and t in "aren't", while .split(' ') won't.
Output of your example code:
print count_words('I was 09809 home -- Yes! yes! You was');
#{"i"=>1, "was"=>2, "09809"=>1, "home"=>1, "yes"=>2, "you"=>1}
def count_words(string)
string.scan(/\w+/).reduce(Hash.new(0)){|res,w| res[w.downcase]+=1;res}
end
Second variant:
def count_words(string)
string.scan(/\w+/).each_with_object(Hash.new(0)){|w,h| h[w.downcase]+=1}
end
def count_words(string)
Hash[
string.scan(/[a-zA-Z]+/)
.group_by{|word| word.downcase}
.map{|word, words|[word, words.size]}
]
end
puts count_words 'I was 09809 home -- Yes! yes! You was'
This code will ask you for input and then find the word frequency for you:
puts "enter some text man"
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new(0)
words.each { |word| frequencies[word.downcase] += 1 }
frequencies = frequencies.sort_by {|a, b| b}
frequencies.reverse!
frequencies.each do |word, frequency|
puts word + " " + frequency.to_s
end
This works, and ignores the numbers:
def get_words(my_str)
my_str = my_str.scan(/\w+/)
h = Hash.new(0)
my_str.each do |s|
s = s.downcase
if s !~ /^[0-9]*\.?[0-9]+$/
h[s] += 1
end
end
return h
end
print get_words('I was there 1000 !')
puts '\n'
You can look at my code that splits the text into words. The basic code would look as follows:
sentence = "Ala ma kota za 5zł i 10$."
splitter = SRX::Polish::WordSplitter.new(sentence)
histogram = Hash.new(0)
splitter.each do |word,type|
histogram[word.downcase] += 1 if type == :word
end
p histogram
You should be careful if you wish to work with languages other than English, since in Ruby 1.9 the downcase won't work as you expected for letters such as 'Ł'.
class String
def frequency
self.scan(/[a-zA-Z]+/).each.with_object(Hash.new(0)) do |word, hash|
hash[word.downcase] += 1
end
end
end
puts "I was 09809 home -- Yes! yes! You was".frequency