Calculating Event Horizons in Ruby - ruby

this is my first post here. I started using Ruby just 2 days ago and think it is an amazing language, however I have been getting stuck. My problem is I am wanting to calculate the event horizon of a black hole given an input defined in the code as "m" This will then be put into a calculation and the size then printed out to the screen. I did need it to be in binary and thats where I am having the issue.
Here is my code so far.
#Event Horizon Calculation Program
G = 6.67*10**-11
m = 20
C = 200000
R = G*m/(C**2)
puts "Here is the result in Binary."
R.to_i(2)
puts R
Now I do realise that the number are not accurate, that dosen't matter at the moment. I just need the function to work.
Thankyou,
Ross.

Your post is not even in a format of asking a question, but guessing from what you wrote, it seems that you are asking how to change your code so that it accepts an input to m and outputs the result. My answer is based on this assumption.
In order to take an input, use the 'gets' method. So, you may want to replace your 'm = 20' line with:
m = gets.to_f
'gets' accepts an input as a string, so you need to convert it to a numeric. to_f changes a string into a float. You can use to_i instead if you want an integer.
You have a line 'R.to_i(2)', and it seems like you want to output this, but you have two problems here. First of all, whatever that creates, it is only creating something in that position, and does not change the value of R, so, in effect, it actually does nothing. Second, ruby can accept numerals in source code written in different bases such decimal, binary, hex, etc., but it only has one internal representation, and you cannot output a numeral in binary. For your purpose, you need to convert it to a string that corresponds to a binary expression. For that, use the 'to_s' method. In fact, the 'to_i' method does not take an argument. Delete your line 'R.to_i(s)', and replace the line 'puts R' with:
puts R.to_s(2)

Related

String include weird behavior

I was doing a code golf (use the minimum number of characters) and I had the following working Python solution. I was trying to shorten my code by re-writing it to Ruby but my Ruby code would always print false.
The code had to read two strings, to ignore the case and to tell whether it was possible to obtain one string by rotating the other string. The output had to be either true or false. Do you have any idea what I did wrong in Ruby?
Python 3 (64 characters) - Works
a=input().lower()
b=input().lower()
print(str(a in 2*b).lower())
Ruby (47 characters) - Always prints "false"
a=gets.upcase
b=gets.upcase
p (b*2).include? a
With the examples I can think of, the Ruby code works correctly, but for some reason, it didn't work on the code golf site (codingame.com, the problem was proposed by user "10100111001").
In Ruby gets includes the \n at the end. You'd have to .chomp it away before doing anything.
a=gets.chomp.upcase
b=gets.chomp.upcase
p (b*2).include? a
By the way, this is not the right way to "tell whether it was possible to obtain one string by rotating the other string", it only partially solves the problem, hope you know that.

Count the number of sentences in a paragraph using Ruby

I have gotten to the point where I can split and count sentences with simple end of sentence punctuation like ! ? .
However, I need it to work for complex sentences such as:
"Learning Ruby is a great endeavor!!!! Well, it can be difficult at times..."
Here you can see the punctuation repeats itself.
What I have so far, that works with simple sentences:
def count_sentences
sentence_array = self.split(/[.?!]/)
return sentence_array.count
end
Thank you!
It's pretty easy to adapt your code to be a little more forgiving:
def count_sentences
self.split(/[.?!]+/).count
end
There's no need for the intermediate variable or return.
Note that empty strings will also be caught up in this, so you may want to filter those out:
test = "This is junk! There's a space at the end! "
That would return 3 with your code. Here's a fix for that:
def count_sentences
self.split(/[.?!]+/).grep(/\S/).count
end
That will select only those strings that have at least one non-space character.
class String
def count_sentences
scan(/[.!?]+(?=\s|\z)/).size
end
end
str = "Learning Ruby is great!!!! The course cost $2.43... How much??!"
str.count_sentences
#=> 3
(?=\s|\z)/) is a positive lookahead, requiring the match to be immediately followed by a whitespace character or the end of the string.
String#count might be easiest.
"Who will treat me to a beer? I bet, alexnewby will!".count('.!?')
Compared to tadman's solution, no intermediate array needs to be constructed. However it yields incorrect results if, for instance, a run of periods or exclamation mark is found in the string:
"Now thinking .... Ah, that's it! This is what we have to do!!!".count('.!?')
=> 8
The question therefore is: Do you need absolute, exact results, or just approximate ones (which might be sufficient, if this is used for statistical analysis of, say, large printed texts)? If you need exact results, you need to define, what is a sentence, and what is not. Think about the following text - how many sentences are in it?
Louise jumped out of the ground floor window.
"Stop! Don't run away!", cried Andy. "I did not
want to eat your chocolate; you have to believe
me!" - and, after thinking for a moment, he
added: "If you come back, I'll buy you a new
one! Large one! With hazelnuts!".
BTW, even tadman's solution is not exact. It would give a count of five for the following single sentence:
The IP address of Mr. Sloopsteen's dishwasher is 192.168.101.108!

Selecting key words in a string (that are included in an Array) to change their format in Ruby

Select key words in a string to change their format in Ruby
I have a big string (text) and an Array of strings (key_words) as below:
text = 'So in this election, we cannot sit back and hope that everything works out for the best. We cannot afford to be tired or frustrated or cynical. No, hear me. Between now and November, we need to do what we did eight years ago and four years ago…'
key_words = ['frustrated', 'tired', 'hope']
My objective is to print each word in ‘text’ while changing the colour and case of the words that are included in key_words. I’ve been able to do that by doing:
require 'colorize'
text.split(/\b/).each do |x|
if key_words.include?(x.downcase) ; print '#{x}'.colorize(:red)
else print '#{x}' end
end
However, since I don’t want to include many words in key_words I want to make the selection more sensitive going beyond an exact match. Such as if, for example:
key_words = ['frustrat', 'tire', 'hope'] => the algorithm would select both 'Frustration', 'Frustrated' or 'Tiring' and 'Tired' or 'Hope' and 'Hopeful'.
I’ve tried playing with word lengths in both the string and the array as below but it’s seems very inefficient solution and I’m getting very confused with the usage of .any? and .include? methods in this scenario.
key_words = ['frustrated', 'tired', 'hope']
key_words_abb = []
key_words.each { |x| key_words_abb << x.downcase[0][0..x.length-2]}
text.split(/\b/).each do |x|
if key_words_abb.include?(x.downcase[0][0..x.length-2]); print '#{x}'.colorize(:red)
else print x
end
end
Since I can’t find a specific solution online I would appreciate your help.
It's worth noting that when doing repeated substitutions on strings, especially longer ones, you'll want your substitution method to be as efficient as possible. Spinning through an array of things to switch out is painfully expensive, especially as that list grows.
Here's a variation on your approach:
replacement = Regexp.new('\b%s\b' % [ Regexp.union(key_words) ])
replaced = text.gsub(replacement) do |s|
s.colorize(:red)
end
puts replaced
If you're using that substitution repeatedly you should persist the Regexp object into a constant. That avoids having to compile it for each string you're adjusting. If the list changes based on factors hard to predict, leave it like this and produce it dynamically.
One thing to note about using Ruby is it's often best to express your code as a series of transformations with output as a final step. Putting things like print in the middle of a loop complicates things unnecessarily. If you want to add an additional step to your loop you have to do a lot of extra work to move that print to a later stage. With the approach here you can just chain on the end and do whatever you want.

Ruby Exponent Issue

When I run this script:
pi=3.14
NozzleAreaM=.005**2*pi.to_f
It returns 7.85e-05 instead of 0.000078 like it does on a normal calculator. I've looked everywhere and I can't find a fix to this problem.
You just need to tell ruby in what format you want to display the float:
pi = 3.14
nozzle_area = 0.005**2 * pi
printf "%.8f \n", nozzle_area
--output:--
0.00007850
See prinf/sprinf here:
http://www.ruby-doc.org/core-2.2.0/Kernel.html#method-i-sprintf
Note that displaying a float in a certain format does not affect how ruby stores the float internally.
Also, writing code like this is fine:
pi=3.14
NozzleAreaM=.005**2*pi.to_f
...as long as you never need to show your code to anyone else. If you want to ask questions about your code, then you need to write legible code. That means you should NOT cram every thing together with no spaces.
In addition, variables that start with a capital letter are constants in ruby. If you do not know what that means yet, just live by this rule: do not capitalize any of your variable names.
Also, your pi variable is already a float (because it has a decimal point), so calling to_f() is unnecessary.
Also, ruby provides pi as a constant in the Math module(the Math module is required automatically):
nozzle_area = 0.005**2 * Math::PI
printf "%.8f \n", nozzle_area
--output:--
0.00007854

Taking fixnum as user input

I was wondering if there is a way to take user input as a fixnum. I can do something like a = gets.chomp.to_i, but is there anything similar in ruby to nextInt() in java, or do I need to do these conversions each time?
When you're working with input streams, like a file or the terminal, you're working with raw bytes. You never work directly with primitive types. If you want primitive types, you have to use methods to make sense of the bytes. In many cases, "working with raw bytes" is synonymous with working with strings, so strings types often have conversion methods to extract typed data out of them.
Java has the Scanner class, which does have a nextInt() method. It is used to extract a Java integer out of text. It does so by parsing the text and converting it to the requested primitive data type, in this case int. In order for it to work, you must give it an input source. When you wrap it around System.in, you get a Scanner that extracts data from standard input, which is usually connected to the terminal.
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
In Ruby, we can simply ask the string to try and convert itself to another type. If you want an integer:
line = gets # reads from standard input
i = line.to_i # converts the string to an integer
String's to_i method performs a very loose conversion, and returns zero if it couldn't figure out the number or if there was no number to begin with. It will never raise an exception and will always return a number, even if there was no number to parse.
The Integer() method performs a more strict conversion.
First of all, your gets.chomp.to_i works, but is not the right way. I don't know how you got that idea to attach chomp, but that has no meaning here. You should do gets.to_i. So, no, you don't need to do the conversion gets.chomp.to_i each time.
And the only thing Ruby can receive from a terminal input is a string. There is no way to receive anything other than a string from the terminal.

Resources